我希望 a 被四舍五入为 13.95.
>>>一种13.949999999999999>>>回合(a, 2)13.949999999999999round 函数没有按照我预期的方式工作.
解决方案您遇到了老问题 带有浮点数,并非所有数字都可以精确表示.命令行只是从内存中向您显示完整的浮点形式.
使用浮点表示,您的四舍五入版本是相同的数字.由于计算机是二进制的,它们将浮点数存储为整数,然后将其除以 2 的幂,因此 13.95 将以类似于 125650429603636838/(2**53) 的方式表示.
双精度数的精度为 53 位(16 位),常规浮点数的精度为 24 位(8 位).Python 中的浮点类型使用双精度来存储值.
例如
>>>125650429603636838/(2**53)13.949999999999999>>>234042163/(2**24)13.949999988079071>>>a = 13.946>>>打印(一)13.946>>>打印(%.2f"%a)13.95>>>回合(a,2)13.949999999999999>>>打印(%.2f"%轮(a,2))13.95>>>打印({:.2f}".格式(一))13.95>>>打印("{:.2f}".format(round(a, 2)))13.95>>>打印("{:.15f}".format(round(a, 2)))13.949999999999999如果您只需要两位小数(例如显示货币价值),那么您有几个更好的选择:
I want a to be rounded to 13.95.
>>> a 13.949999999999999 >>> round(a, 2) 13.949999999999999The round function does not work the way I expected.
解决方案You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.
With floating point representation, your rounded version is the same number. Since computers are binary, they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53).
Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.
For example,
>>> 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.949999999999999If you are after only two decimal places (to display a currency value, for example), then you have a couple of better choices:
更多推荐
将浮点数限制为两位小数
发布评论