%g and fpformat.sci()

Tim Peters tim.peters at gmail.com
Thu Jun 30 20:55:08 CEST 2005


[Sivakumar Bhaskarapanditha]
> How can I control the number of digits after the decimal point using the %g
> format specifier.

You cannot.  See a C reference for details; in general, %g is required
to truncate trailing zeroes, and in %<m>.<n>g the <n> is the maximum
number of significant digits displayed (the total number both before
and after the decimal point).

If you need to preserve trailing zeroes, then you need to write code
to do that yourself, or use the %e format code (or maybe even %f). 
For example,

>>> a = 1.234e-5
>>> print "%.6g" % a
1.234e-005
>>> print "%.60g" % a
1.234e-005
>>> print "%.6e" % a
1.234000e-005
>>> print "%.6f" % a
0.000012



More information about the Python-list mailing list