Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 913
Michael Bianconi Avatar asked May 30 '26 19:05

Michael Bianconi


1 Answers

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
like image 127
Jack Fleeting Avatar answered Jun 01 '26 09:06

Jack Fleeting



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!