[Tutor] Is there anyway to set how many numbers are used after thedecimal in floating numbers?

Alan G alan.gauld at freenet.co.uk
Thu Aug 18 23:27:09 CEST 2005


> Is there anyway to set how many numbers are used after 
> the decimal in floating numbers? 

There are a couple of options. Usually you just want
to display the 2 digit accuracy but keep the real value 
as accurate as possible. The easiest way to do that is 
to use format strings (as described in the Simple Sequences 
topic of my tutorial).

Basically:

>>> print "%7.2f" % 123.45678901
 123.46
>>>

Notice the space at the front. I asked Python to print 
the digit with 7 characters and a max of 2 after the 
decimal point (which is itself one of the 7 characters!).

There is a wealth of other options you can use with 
format strings, see my tutor for more examples, or 
the reference documents for the full story.

> It would be nice if the answer could be rounded 
> to 2 decimal spots, instead of the ten millionths spot.

If you really want to round the answer so it always has
two decimal digit precision you can use the round() 
function after multiplying aby 100:

>>> print round(123.4567 * 100)/100
123.46

In theory you can use round itself to do this but because 
of how floats are represented in binary you don't always 
get what you expect:

>>> round(1213.84567,2)
1213.8499999999999
>>>

But usually simply controlling the display witrh a format 
string is all you want to do.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list