Formatted Output - Floating Point Numbers
John Hunter
jdhunter at ace.bsd.uchicago.edu
Sat Nov 16 17:03:15 EST 2002
>>>>> "David" == David Marshall <maximum_hops at yahoo.co.uk> writes:
David> display.divide(57,7) # I only want 2 decimal places
David> returned
You need to be careful of integer division.
In [16]: 57/7
Out[16]: 8
In [17]: 57.0/7
Out[17]: 8.1428571428571423
If you want to insure floating point division, with recent versions of
python do
from __future__ import division
print 57/7
Otherwise, you can do
print float(x)/y
To format 2 significant digits of a floating point number, you can do
print '%1.2f' % (57.0/7)
The man pages of the C function sprintf will tell you a lot about the
format possibilities:
http://www.rt.com/man/sprintf.3.html
John Hunter
More information about the Python-list
mailing list