3

I got a problem in string format function which I don't understand. Please help to explain why and how to fix this. thanks. ( python 2.7.3 , [GCC 4.6.3] on linux2 , ubuntu 12.04 x86 )

>>> import locale
>>> locale.format("%0.{0}f".format(2), 1.135, grouping=True)
'1.14'
>>> locale.format("%0.{0}f".format(2), 1.125, grouping=True)
'1.12'

>>> ("%0.2f")%(1.135)
'1.14'
>>> ("%0.2f")%(1.125)
'1.12'

I need the format result to match the round() function

>>> round(1.135, 2)
1.14
>>> round(1.125, 2)
1.13

Thank everyone.

2
  • 3
    Why don't you round it first before printing it? Commented Nov 27, 2012 at 4:43
  • So, interestingly in my python3 build, round() returns results that match the string formatting. Commented Nov 27, 2012 at 4:51

1 Answer 1

1

That's because rounding is not simply bringing the last digit greater than 5 up, while truncating those lower than 4, since this method would introduce an increase in the expected average of rounded numbers.

The solution is to use Bankers' Rounding, that's what you see here.

Sign up to request clarification or add additional context in comments.

2 Comments

That doesn't answer the question: why is there a difference between round and format. As far as I've been able to determine it's a combination of the inability to exactly represent decimal numbers in binary format and the rounding algorithm used in both functions.
Bankers Rounding is very cool -- but that's not what Python 2.7 is doing (at least on my machine!) e.g. I tried 0.605, 0.615, 0.625, 0.635 etc. and only 0.625 fails to round up. The OP's issue was 1/8; this is at 5/8; hmm....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.