pythonfloating-pointdecimalf-string

Truncate f-string float without rounding


I want to print a very very close-to-one float, truncating it to 2 decimal places without rounding, preferably with the least amount of code possible.

a = 0.99999999999
print(f'{a:0.2f}')
Expected: 0.99
Actual: 1.00

Solution

  • I don't think you need f-strings or math functions, if I understand you correctly. Plain old string manipulation should get you there:

    a = 0.987654321
    print(str(a)[:4])
    

    output:

    0.98