سؤال

$ 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'

So far, so good. But now:

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

"111.17" instead of the expected "111.18". I think I understand what and why happens, but I need ideas how to get the expected result. Both Excel and OpenOffice Calc show "111.18", therefore somehow it should be possible.

هل كانت مفيدة؟

المحلول

You can use the decimal module here:

>>> 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')
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top