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

Alan Gauld alan.gauld at btinternet.com
Thu Oct 24 01:13:25 CEST 2013


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.

However, for the purposes of your homework  we will ignore that.

> How do I incorporate that into my current code below? The textbook I'm
> using doesn't describe how to do that. Thanks in advance.

You need tobdistinguish between storage and display. You want to 
maintain the data stored in its full accuracy but display it with
only 2 decimal digits. One waty to do that is with the string format 
method (I'm assuming Python v3). Check the Python docs for string 
formatting and you will find several options you can use to control the 
display of floating point numbers.

The basic form is

print( "Here is a float: {}".format(123.456789) )

We can limit the field length to 7 digit swith

print( "Here is a float: {:15f}".format(123.456789) )

And adjust the number of digits after the point like so:

print( "Here is a float: {:7.3f}".format(123.456789) )

You can also specify justification, zero padding and other aspects.
Read the docs...

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list