How to round float down to a given precision?

谁说我不能喝 提交于 2020-05-27 04:56:21

问题


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

回答1:


Something like this should work for whatever 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:


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



回答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)
    return floor(num * multiplier) / multiplier



回答4:


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

Patch the code with more checks like precision is not negative among others.



来源:https://stackoverflow.com/questions/37712306/how-to-round-float-down-to-a-given-precision

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!