[issue5118] '%.2f' % 2.545 doesn't round correctly
Mark Dickinson
report at bugs.python.org
Sat Jan 31 16:14:09 CET 2009
Mark Dickinson <dickinsm at gmail.com> added the comment:
> print round(2.545, 2) // returns 2.55
Aha! Yes, that one *is* a bug (see issue #1869), though it's not one that
I regard as terribly serious, and not one that can be easily solved in all
cases.
Here's why I don't see it as particularly serious: you're rounding a value
that's just on the boundary: 2.545+tiny_error should round up, while
2.545-tiny_error should round down. But tiny (or not-so-tiny) errors are
an almost unavoidable part of working with binary floating-point
arithmetic. Additionally, whether the binary approximation stored for
2.545 is less than or greater than the true value depends on many things
(format of a C double, system C library function used for string-to-double
conversion, etc.), so in a sense either 2.55 *or* 2.54 can be defended as
a valid result, and a good numeric programmer won't write code that
depends on getting one or the other.
Having said that, if you're interested in providing a patch for issue
#1869 I'd certainly take a look.
If you care about *exact* representations of numbers with a finite number
of places after the decimal point, you may be interested in Python's
'decimal' module.
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue5118>
_______________________________________
More information about the Python-bugs-list
mailing list