【问题标题】:simple rounding down decimal places简单的四舍五入小数位
【发布时间】:2021-03-06 06:05:56
【问题描述】:

我编写了一个简单的函数,通过使用内置的舍入函数根据一定的小数位数对数字进行舍入,如果舍入,则将最后一个小数减去 1。

def rounddown(number, places):
    rounded = round(number, places)
    if rounded > number:
        string = '1'
        for x in range(places):
            string = string + '0'
        return rounded - (1/float(string))
    else:
        return rounded

我的问题是有时结果会变成这样的数字:

rounddown(4.555756, 5)

4.555750000000001

有人可以向我解释一下这里到底发生了什么吗?我认为这可能与浮点数学不准确有关?

谢谢

【问题讨论】:

标签: python-3.x


【解决方案1】:

问题基本上是浮点运算,以避免问题 请使用如下所示的十进制库

from decimal import Decimal
def rounddown(number, places):
    rounded = round(number, places)
    if rounded > number:
        string = '1'
        for x in range(places):
            string = string + '0'
        return Decimal(str(rounded))-1/Decimal(string)
    else:
        return rounded 

【讨论】:

    猜你喜欢
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多