我希望a四舍五入到13.95。我试过用圆形,但我得到:
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
有关标准库Decimal类的类似问题,请参阅How can I format a Decimal to always show 2 Decimal places?。
我希望a四舍五入到13.95。我试过用圆形,但我得到:
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
有关标准库Decimal类的类似问题,请参阅How can I format a Decimal to always show 2 Decimal places?。
当前回答
有新的格式规范,字符串格式规范迷你语言:
您可以执行以下操作:
"{:.2f}".format(13.949999999999999)
注1:上面返回一个字符串。为了获得float,只需用float(…)包装:
float("{:.2f}".format(13.949999999999999))
注意2:用float()换行不会改变任何内容:
>>> x = 13.949999999999999999
>>> x
13.95
>>> g = float("{:.2f}".format(x))
>>> g
13.95
>>> x == g
True
>>> h = round(x, 2)
>>> h
13.95
>>> x == h
True
其他回答
您可以修改输出格式:
>>> a = 13.95
>>> a
13.949999999999999
>>> print "%.2f" % a
13.95
大多数数字不能用浮点数精确表示。如果你想舍入这个数字,因为这是你的数学公式或算法所要求的,那么你想使用舍入。如果您只想将显示限制为某一精度,那么甚至不要使用舍入,只需将其格式化为字符串即可。(如果您想用其他舍入方法显示,并且有吨,则需要混合使用这两种方法。)
>>> "%.2f" % 3.14159
'3.14'
>>> "%.2f" % 13.9499999
'13.95'
最后,也许最重要的是,如果你想要精确的数学,那么你根本不需要浮点数。通常的例子是处理货币,并将“美分”存储为整数。
这很简单,比如:
使用十进制模块进行快速正确舍入的十进制浮点运算:d=十进制(10000000.0000009)为了实现舍入:d.quantite(十进制('0.01'))将产生十进制('10000000.00')使上述干燥:def round_decimal(数字,指数='0.01'):decimal_value=十进制(数字)return decimal_value.g量化(十进制(指数))或定义round_decimal(数字,小数位数=2):decimal_value=十进制(数字)return decimal_value.g量化(十进制(10)**-decimal_places)
PS:对其他人的批评:格式不是舍入。
为了修复Python和JavaScript等类型动态语言中的浮点,我使用了这种技术
# For example:
a = 70000
b = 0.14
c = a * b
print c # Prints 980.0000000002
# Try to fix
c = int(c * 10000)/100000
print c # Prints 980
您还可以按以下方式使用Decimal:
from decimal import *
getcontext().prec = 6
Decimal(1) / Decimal(7)
# Results in 6 precision -> Decimal('0.142857')
getcontext().prec = 28
Decimal(1) / Decimal(7)
# Results in 28 precision -> Decimal('0.1428571428571428571428571429')
有新的格式规范,字符串格式规范迷你语言:
您可以执行以下操作:
"{:.2f}".format(13.949999999999999)
注1:上面返回一个字符串。为了获得float,只需用float(…)包装:
float("{:.2f}".format(13.949999999999999))
注意2:用float()换行不会改变任何内容:
>>> x = 13.949999999999999999
>>> x
13.95
>>> g = float("{:.2f}".format(x))
>>> g
13.95
>>> x == g
True
>>> h = round(x, 2)
>>> h
13.95
>>> x == h
True