我希望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?。
当前回答
它正按照您的指示执行,并且工作正常。阅读更多关于浮点混淆的内容,并尝试使用十进制对象。
其他回答
请尝试以下代码:
>>> a = 0.99334
>>> a = int((a * 100) + 0.5) / 100.0 # Adding 0.5 rounds it up
>>> print a
0.99
有新的格式规范,字符串格式规范迷你语言:
您可以执行以下操作:
"{:.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
我们有多种选择:
选项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)
orig_float = 232569 / 16000.0
14.5355625
short_float = float("{:.2f}".format(orig_float))
14.54
Use
print"{:.2f}".format(a)
而不是
print"{0:.2f}".format(a)
因为后者在尝试输出多个变量时可能会导致输出错误(请参见注释)。