Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 2.7 string format to decimal as round function

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.

like image 482
Hardy Avatar asked Jul 24 '26 12:07

Hardy


1 Answers

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.

like image 146
starrify Avatar answered Jul 26 '26 04:07

starrify



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!