为什么 str() 会向上舍入浮点数? [英] Why does str() round up floats?
问题描述
Python 内置的 str() 函数在传入带有许多小数的浮点数时会输出一些奇怪的结果.事情是这样的:
<预><代码>>>>str(19.9999999999999999)>>>'20.0'我希望得到:
<预><代码>>>>'19.9999999999999999'有人知道为什么吗?也许可以解决它?
谢谢!
四舍五入不是 str()
,而是您首先使用浮点数的事实.浮点类型速度快,但精度有限;换句话说,它们设计不精确.这适用于所有编程语言.有关浮点问题的更多详细信息,请阅读每个程序员都应该了解的关于浮点运算的知识"
如果你想存储并操作精确的数字,使用decimal
模块:
The built-in Python str() function outputs some weird results when passing in floats with many decimals. This is what happens:
>>> str(19.9999999999999999)
>>> '20.0'
I'm expecting to get:
>>> '19.9999999999999999'
Does anyone know why? and maybe workaround it?
Thanks!
It's not str()
that rounds, it's the fact that you're using floats in the first place. Float types are fast, but have limited precision; in other words, they are imprecise by design. This applies to all programming languages. For more details on float quirks, please read "What Every Programmer Should Know About Floating-Point Arithmetic"
If you want to store and operate on precise numbers, use the decimal
module:
>>> from decimal import Decimal
>>> str(Decimal('19.9999999999999999'))
'19.9999999999999999'
这篇关于为什么 str() 会向上舍入浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!