[Tutor] Want to keep to two decimal places for currency

Danny Yoo dyoo at hashcollision.org
Thu Oct 24 05:44:04 CEST 2013


On Wed, Oct 23, 2013 at 4:13 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> On 23/10/13 22:39, Shelby Martin wrote:
>
>> I've looked online but I'm confused - I need to keep it so that the
>> following program limits the output to two decimal places since it deals
>> in currency.
>>
>
> Its generally a bad idea to use floats when dealing with currency since
> they can introduce small errors which can accumulate over time. It's better
> to either use the Decimal module or to convert money to cents/.pennies and
> then convertback to dollars for display purposes.
>


Hi Shelby,


If you want to read some gory details, you can find the reasons for why
it's unsafe to represent currency with "floating point" numbers.  There's a
classic paper called "What Every Computer Scientist Should Know About
Floating-Point Arithmetic":

    http://www.validlab.com/goldberg/paper.pdf

and you probably don't want to read the whole thing.  :P  A rough gist of
the problem: traditional, engineering-focused computer math has a
particular trade-off that most programmers do not realize at first: it
trades accuracy for speed.  The native hardware of your computer does
calculations in base-2 rather than base-10 arithmetic.  Unfortunately, that
means that fractional quantities take a representational hit: your computer
cannot accurately represent certain decimals in base-2.

It turns out that this floating point arithmetic limitation is not so bad
for a lot of important applications.  But it doesn't bode well at all for
applications that deal with money.  There are libraries in Python that
avoid using the built-in floating point hardware, such as the Decimal
library that Alan noted.  Computations with it are slower, but that's an
acceptable price for getting the dollars and cents right.  If we would do
this sort of thing in the real world, we'd use something like the Decimal
library.  You'll see equivalent kinds of libraries in other programming
languages, like the BigDecimal class in Java.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131023/afaa7240/attachment.html>


More information about the Tutor mailing list