I am looking into rounding floating point numbers in Python and the following behavior seems quite strange:
Code:
a = 203.25
print '%.2f'%(a/10.)
print '%.2f'%(round(a/10., 2))
print '%.2f'%(0.1*a)
Output:
20.32
20.32
20.33
Why does the first and especially the second case fail?
http://en.wikipedia.org/wiki/Rounding#Round_half_to_even
So the real question should be why does the third case fail?
203.25can be expressed exactly in the floating point representation, however0.1cannot, it turns out to be a tiny bit more than0.1So it gets rounded up