Recently, I learned art of string formatting in Python 2.7.
I decided to play with floating point numbers.
Came across an awkward looking solution, as written below.
print "%.0f"%45.5000000 #46 print "%.0f"%0.5000000 #0 #Why??
BUT
print int(round(45.5000000)) #46 print int(round(0.5000000)) #1
Please help me understand, why this behavior is shown by %f
.
Advertisement
Answer
The internal implementation for the %.0f
string format uses a round-half-even rounding mode.
In Python 2, the round()
function uses round-away-from-zero. In Python 3, that was changed to round-half-even making it consistent with string formatting.
FWIW, the decimal module offers you a choice of rounding modes if you want more control than afforded by round()
or by string formatting. The decimal rounding modes are: ROUND_05UP ROUND_CEILING ROUND_DOWN ROUND_FLOOR ROUND_HALF_DOWN ROUND_HALF_EVEN ROUND_HALF_UP ROUND_UP.