Truncate a decimal value in Python

visakh picture visakh · Dec 12, 2013 · Viewed 20.7k times · Source

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.

Answer

Nilani Algiriyage picture Nilani Algiriyage · Dec 12, 2013

You can use following code

import decimal
d = 0.989434

print decimal.Decimal(d).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)