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 &
Solution 1:
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
Solution 2:
Something like this should work for whatever number of digits you want to do:
>>>import math>>>defround_down(num,digits):
factor = 10.0 ** digits
return math.floor(num * factor) / factor
>>>round_down(2.667,2)
2.66
Solution 3:
You can use math.floor
to "round down" to the nearest whole number. So to round to the 3rd decimal place, you can try math.floor(1000*number) / 1000
.
In general, to "round down" a number num
to precision n
, you can try:
from math import floor
def round_down(num, n):
multiplier =pow(10,n)
returnfloor(num * multiplier) / multiplier
Solution 4:
You can also play around this using strings
defround_down(num, prec):
ifisinstance(num, float):
s = str(num)
returnfloat(s[:s.find('.') + prec + 1])
else:
raise ValueError
round_down(2.6667, 2)
# 2.66
Patch the code with more checks like precision is not negative among others.
Post a Comment for "How To Round Float Down To A Given Precision?"