Python 2.7 round 1 十进制不正确

Rob*_*ert 2 rounding python-2.7

小数点后 1 位四舍五入工作不正确:

见下文:

round(11.35, 1)
11.3

round(1.35, 1)
1.4
Run Code Online (Sandbox Code Playgroud)

如何在 Python 中解决这个问题?

这个问题的解决方法是:

def round_decimal(value, rounding):
    number = decimal.Decimal(str(value))
    decimal_point = float("1e%d" % -rounding)
    return float(number.quantize(decimal.Decimal(str(decimal_point))))
Run Code Online (Sandbox Code Playgroud)

Ste*_*ker 5

这是一般计算机中小数表示的问题(因此非 Python 特有)。

我认为解决这个问题的方法是使用标准库模块decimal。在您的情况下,它看起来像这样:

num1 = decimal.Decimal("11.35")
print num1.quantize(decimal.Decimal("0.1")) # round to one decimal
# output: 11.4

num2 = decimal.Decimal("1.35")
print num2.quantize(decimal.Decimal("0.1"))
# output: 1.4
Run Code Online (Sandbox Code Playgroud)