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
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
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