[Tutor] Python 2.5.4 - error in rounding
Alan Gauld
alan.gauld at btinternet.com
Fri May 21 23:51:31 CEST 2010
"Neven Gorsic" <neven.gorsic at gmail.com> wrote
> I run into Python error in rounding and not know how to predict when
> it will
> occur in order to prevent wrong result.
It depends how you define wrong. When I was at scvhool the rules f
or rounding decimals said that if it ended in 5 you rounded to the
nearest even digit.
So 0.45 -> 0.4 and 0.55 ->0.6
But you seem to assume a 5 always rounds up...
> What can I do to assure accurate result?
Just to be picky, Python is being accurate, but it is
accurately reflecting the binary value... But I think
you knew that! :-)
>
>>>> "%.2f" % 0.465
> '0.47' correct
>>>> "%.2f" % 0.475
> '0.47' not correct
>>>> "%.2f" % 0.485
> '0.48' not correct
The good news is that python's round() function seems
to have had the same teacher as you :-)
So
>>>> "%.2f" % round(0.475,2)
> '0.48'
>>>> "%.2f" % round(0.485, 2)
> '0.49'
HTH,
Alan G.
More information about the Tutor
mailing list