Search code examples
pythonfloating-pointformatprecisionprompt

Python format float with three dots is possible?


I'm trying to format a float like

10 / 3 = Quotient: 3.3333...

42 / 10 = Quotient: 4.2

i want to add three dots when there are more than 4 decimal places

for the moment i have that format

print("{:{width}}{:.5g}".format("Quotient:", a / b, width=width))

result of this format :

10 / 3 = Quotient: 3.3333

42 / 10 = Quotient: 4.2

how can i do that with format() or another function in py standard lib ?


Solution

  • You could create a helper function such as print_float to format the float and print it, using a "reverse and find" approach as suggested here:

    def print_float(f: float) -> None:
        float_str = str(f)
        num_decimal_places = float_str[::-1].find('.')
        if num_decimal_places > 4:
            print(float_str[:-num_decimal_places + 4], '...', sep='')
        else:
            print(float_str)
    

    Results:

    print_float(12345)     # 12345
    print_float(10 / 3)    # 3.3333...
    print_float(42 / 10)   # 4.2
    print_float(1.999999)  # 1.9999...
    

    Finally, here's a (potentially) more efficient solution, which doesn't involve doing [::-1] to reverse the string in place. Note that it uses len() in place of a string reversal, which should be an O(1) operation in any case.

    def print_float(f: float, max_decimal_places=4) -> None:
        float_str = str(f)
        len_float = len(float_str)
        idx_after_point = float_str.find('.') + 1
    
        if len_float - idx_after_point > max_decimal_places and idx_after_point:
            print(float_str[:idx_after_point + max_decimal_places] + '...')
        else:
            print(float_str)