How to replace all occurrences of a specific digit in a floating-point number with Python

1 Answer

0 votes
def replace_all_digits(num: float, old_digit: str, new_digit: str) -> float:
    # Format the number to a string with 3 decimal places
    str_num = f"{num:.3f}"

    # Replace all occurrences of old_digit with new_digit
    modified_str = str_num.replace(old_digit, new_digit)

    # Convert the modified string back to float
    return float(modified_str)

# Output results
print(f"{replace_all_digits(82420.291, '2', '7'):.3f}")
print(f"{replace_all_digits(111.11, '1', '5'):.3f}")



'''
run:

87470.791
555.550

'''

 



answered 19 hours ago by avibootz

Related questions

...