python - 看起来有错误的路由的解决方法

标签 python floating-accuracy

$ python
Python 2.7.3 (default, Apr 19 2012, 11:28:02) 
[GCC 4.5.3 20120403 (ALT Linux 4.5.3-alt3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> g = 1.175
>>> "%0.2f" % g
'1.18'
>>> g = 11.175
>>> "%0.2f" % g
'11.18'

到目前为止,一切都很好。但现在:

>>> g = 111.175
>>> "%0.2f" % g
'111.17'

“111.17”而不是预期的“111.18”。我想我明白发生了什么以及为什么会发生,但我需要如何获得预期结果的想法。 Excel 和 OpenOffice Calc 都显示“111.18”,因此应该是可能的。

最佳答案

您可以使用decimal模块在这里:

>>> import decimal
>>> myothercontext = decimal.Context(rounding=decimal.ROUND_HALF_UP)
>>> decimal.setcontext(myothercontext)
>>> TWOPLACES = decimal.Decimal(10) ** -2
>>> decimal.Decimal('111.175').quantize(TWOPLACES)
Decimal('111.18')
>>> decimal.Decimal('1.175').quantize(TWOPLACES)
Decimal('1.18')
>>> decimal.Decimal('11.175').quantize(TWOPLACES)
Decimal('11.18')

关于python - 看起来有错误的路由的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20489297/

相关文章:

python - 使用 python 在文件中搜索变量并获取其值

While 循环中的 Python Walrus 运算符

c - C/C++中sqrt函数的保证精度

C 对 float 的奇怪近似

减法时的 MATLAB 精度

python - 如何将模式 "begins with A or ends with B"与 Python 正则表达式匹配?

python - 推广小部件并从生成的 ui 中使用它们

python - 加载夹具 Django

Java parsefloat 在每个 CPU 上结果相同

c++ - 查找浮点计数器的最大值