Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 错误查找胭脂的解决方法_Python_Floating Accuracy - Fatal编程技术网

Python 错误查找胭脂的解决方法

Python 错误查找胭脂的解决方法,python,floating-accuracy,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

到目前为止,一切顺利。但现在:

$ 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'
“111.17”而不是预期的“111.18”。我想我知道发生了什么,为什么会发生,但我需要知道如何得到预期的结果。Excel和OpenOffice Calc都显示“111.18”,因此,无论如何,这应该是可能的。

您可以在此处使用该模块:

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

我假设Excel和OpenOffice Calc不使用浮点数,至少不直接在UI中公开。
>>> 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')