我希望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?。
当前回答
对于原始Python:
对于浮点到字符串转换的2个小数点:
a = 13.949999999999999
format(a, '.2f')
对于浮点到浮点转换的2个小数点:
a = 13.949999999999999
round(float(a), 2)
or
float(format(a, '.2f'))
其他回答
它正按照您的指示执行,并且工作正常。阅读更多关于浮点混淆的内容,并尝试使用十进制对象。
我们有多种选择:
选项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)
您可以修改输出格式:
>>> a = 13.95
>>> a
13.949999999999999
>>> print "%.2f" % a
13.95
我使用的方法是字符串切片。它相对快速和简单。
首先,将浮点数转换为字符串,然后选择您希望的长度。
float = str(float)[:5]
在上面的单行中,我们将值转换为字符串,然后将字符串仅保留为其前四位数字或字符(包括)。
希望这有帮助!
有新的格式规范,字符串格式规范迷你语言:
您可以执行以下操作:
"{:.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