Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate a decimal value in Python

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.

like image 473
visakh Avatar asked Dec 12 '13 13:12

visakh


People also ask

How do you truncate to 2 decimal places in Python?

Just use the formatting with %. 2f which gives you round down to 2 decimal points.

How do you truncate a decimal?

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.


1 Answers

You can use following code

import decimal
d = 0.989434

print decimal.Decimal(d).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
like image 132
Nilani Algiriyage Avatar answered Oct 04 '22 10:10

Nilani Algiriyage