Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round float down to a given precision?

I need a way to round a float to a given number of decimal places, but I want to always round down.

For example, instead of

>>> round(2.667, 2)
2.67

I would rather have

>>> round_down(2.667, 2)
2.66
like image 538
Brendan Abel Avatar asked Jun 08 '16 20:06

Brendan Abel


1 Answers

You've got a friend in quantize and ROUND_FLOOR

>>> from decimal import Decimal,ROUND_FLOOR
>>> float(Decimal(str(2.667)).quantize(Decimal('.01'), rounding=ROUND_FLOOR))
2.66
>>> float(Decimal(str(-2.667)).quantize(Decimal('.01'), rounding=ROUND_FLOOR))
-2.67

Note that you can use ROUND_DOWN for positive numbers. As interjay mentions in a comment, ROUND_DOWN Rounds towards zero and hence may return incorrect values for negative numbers.

>>> from decimal import Decimal,ROUND_DOWN
>>> Decimal(str(2.667)).quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('2.66')
>>> float(Decimal(str(2.667)).quantize(Decimal('.01'), rounding=ROUND_DOWN))
2.66
like image 112
Bhargav Rao Avatar answered Nov 24 '22 15:11

Bhargav Rao