我希望a四舍五入到13.95。我试过用圆形,但我得到:

>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999

有关标准库Decimal类的类似问题,请参阅How can I format a Decimal to always show 2 Decimal places?。


当前回答

如果您想处理金钱,请使用Python十进制模块:

from decimal import Decimal, ROUND_HALF_UP

# 'amount' can be integer, string, tuple, float, or another Decimal object
def to_money(amount) -> Decimal:
    money = Decimal(amount).quantize(Decimal('.00'), rounding=ROUND_HALF_UP)
    return money

其他回答

我们有多种选择:

选项1:

x = 1.090675765757
g = float("{:.2f}".format(x))
print(g)

选项2:内置round()支持Python 2.7或更高版本。

x = 1.090675765757
g = round(x, 2)
print(g)

如果您想处理金钱,请使用Python十进制模块:

from decimal import Decimal, ROUND_HALF_UP

# 'amount' can be integer, string, tuple, float, or another Decimal object
def to_money(amount) -> Decimal:
    money = Decimal(amount).quantize(Decimal('.00'), rounding=ROUND_HALF_UP)
    return money

Python教程有一个名为“浮点算术:问题和限制”的附录。阅读它。它解释了正在发生的事情以及为什么Python做得最好。它甚至有一个与您的示例相匹配的示例。让我引用一点:

>>> 0.10.10000000000000001您可能会尝试使用round()函数将其切回单个您期望的数字。但这并不意味着差异:>>>圆形(0.1,1)0.10000000000000001问题是二进制文件为“0.1”存储的浮点值已经是最好的二进制了接近1/10,因此尝试再圆一次也不能让它变得更好:它已经很好了。另一个结果是,由于0.1不是十分之一,加十0.1的值可能不会产生精确的结果1.0,或者:>>>总和=0.0>>>对于范围(10)中的i:…总和+=0.1...>>>总和0.99999999999999989

解决问题的另一种方法是使用十进制模块。

你遇到了一个关于浮点数的老问题,不是所有的数字都能精确表示。命令行只是显示内存中的完整浮点形式。

对于浮点表示法,舍入版本是相同的数字。由于计算机是二进制的,它们将浮点数存储为整数,然后将其除以2的幂,因此13.95将以类似于125650429603636838/(2**53)的方式表示。

双精度数字的精度为53位(16位),常规浮点数的精度为24位(8位)。Python中的浮点类型使用双精度来存储值。

例如

>>> 125650429603636838/(2**53)
13.949999999999999

>>> 234042163/(2**24)
13.949999988079071

>>> a = 13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a, 2))
13.95
>>> print("{:.2f}".format(a))
13.95
>>> print("{:.2f}".format(round(a, 2)))
13.95
>>> print("{:.15f}".format(round(a, 2)))
13.949999999999999

如果您只在小数点后两位(例如显示货币值),那么您有两个更好的选择:

使用整数并以美分而非美元存储值,然后除以100转换为美元。或者使用小数等固定点数。

在Python中,可以使用格式运算符将值舍入到两位小数:

print(format(14.4499923, '.2f')) // The output is 14.45