How to round a float to a given accuracy?

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

For example, instead of

>>> round(2.667, 2)
2.67

I prefer

>>> round_down(2.667, 2)
2.66
+4
source share
4 answers

Something like this should work for any number of digits you want to do:

>>> import math
>>> def round_down(num,digits):
        factor = 10.0 ** digits
        return math.floor(num * factor) / factor

>>> round_down(2.667,2)
2.66
+2
source

You have a friend in quantizeandROUND_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

Please note that you can use ROUND_DOWNfor positive numbers. As interjay mentions in the commentary , ROUND_DOWNrounds are zero and therefore 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
+5
source

math.floor . , , math.floor(1000*number) / 1000.

In general, to "round" a number numto precision n, you can try:

from math import floor

def round_down(num, n):
    multiplier = pow(10,n)
    return floor(num * multiplier) / multiplier
+1
source

You can also play around this using strings.

def round_down(num, prec):
    if isinstance(num, float):
        s = str(num)
        return float(s[:s.find('.') + prec + 1])
    else:
        raise ValueError

round_down(2.6667, 2)
# 2.66

Replacing code with a large number of checks, such as accuracy, is not negative among others.

0
source

All Articles