[Tutor] Rounding Error

Devin Jeanpierre jeanpierreda at gmail.com
Sat Jan 28 08:06:33 CET 2012

On Sat, Jan 28, 2012 at 1:20 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> And finally, we come all the way back to the beginning again and say That's
> not the right way to do it! Don't round the number *outside* of the string
> formatting, get the string formatting to do it for you:

Reason being because repr(round(0.1, 2)) != '0.1' (on older Pythons).
String formatting does the right thing.

Also don't use floats for currency, they can attract rounding errors
and can't represent many common amounts with 100% precision, the way a
Decimal or Fraction can (see decimal, fractions modules). For example,
it can't represent 0.1 exactly, thus leading to the above situation.

-- Devin

More information about the Tutor mailing list