How to replace a digit in a floating-point number by index with Python

1 Answer

0 votes
def replace_float_digit(number: float, position: int, new_digit: str) -> float:
    # Validate that newDigit is indeed a single digit
    if not new_digit.isdigit() or len(new_digit) != 1:
        raise ValueError("Replacement must be a single digit (0-9).")

    # Convert number to string with fixed precision (10 decimal places)
    str_num = f"{number:.10f}"

    # Validate position
    if position < 0 or position >= len(str_num):
        raise IndexError("Position is out of range for the number string.")

    # Ensure position points to a digit
    if str_num[position] in ('.', '-'):
        raise ValueError("Position points to a non-digit character.")

    # Replace digit
    modified = str_num[:position] + new_digit + str_num[position+1:]

    # Convert back to float
    return float(modified)


def main():
    try:
        num = 89710.291
        pos = 2   # 0-based index
        new_digit = '8'

        result = replace_float_digit(num, pos, new_digit)
        print(f"Modified number: {result:.3f}")
    except Exception as e:
        print(f"Error: {e}")


if __name__ == "__main__":
    main()



'''
run:

Modified number: 89810.291

'''

 



answered 1 day ago by avibootz
...