I am trying to truncate a decimal value in Python. I don't want to round it, but instead just display the decimal values upto the specified accuracy. I tried the following:
d = 0.989434
'{:.{prec}f}'.format(d, prec=2)
This rounds it to 0.99. But I actually want the output to be 0.98. Obviously, round()
is not an option. Is there any way to do this? Or should I go back to the code and change everything to decimal
?
Thanks.
Just use the formatting with %. 2f which gives you round down to 2 decimal points.
To truncate a number, we miss off digits past a certain point in the number, filling-in zeros if necessary to make the truncated number approximately the same size as the original number. To truncate a number to 1 decimal place, miss off all the digits after the first decimal place.
You can use following code
import decimal
d = 0.989434
print decimal.Decimal(d).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With