Another approach based on the module is decimalmore sophisticated tools. Like the built-in round(), it also supports negative "digits":
>>> round(1234.5, -1)
1230.0
>>> round(1234.5, -2)
1200.0
>>> round(1234.5, -3)
1000.0
and you can use any of the 8 (!) rounding modes defined in decimal.
from decimal import ROUND_DOWN
def rfloat(x, ndigits=0, rounding=ROUND_DOWN):
from decimal import Decimal as D
proto = D("1e%d" % -ndigits)
return float(D(str(x)).quantize(proto, rounding))
Example:
for i in range(-4, 6):
print i, "->", rfloat(-55555.55555, i)
gives:
-4 -> -50000.0
-3 -> -55000.0
-2 -> -55500.0
-1 -> -55550.0
0 -> -55555.0
1 -> -55555.5
2 -> -55555.55
3 -> -55555.555
4 -> -55555.5555
5 -> -55555.55555
Try to analyze the lines yourself at your own risk; -)
source
share