[Tutor] Meaning of %g ?
Alan Gauld
alan.gauld at freenet.co.uk
Mon Apr 17 11:15:35 CEST 2006
>>>> a = 123456.78
>>>> print "%g\n%e\n%f" % (a,a,a)
> 123457
> 1.234568e+005
> 123456.780000
>Float number loses digits and becomes integer in the output ?
Yep, I am rapidly coming to the comnclusion that %g is broken
in Python. I must do some tests with gcc to see what it does
with %g, it may be the wierd behaviour is coming from there.
I've never used %g with gcc...
> Can we override the %g in python, or adding in some other
> format identifier so that print statement with custom format
> string still works ?
I don't think we can add new format specifiers. It would be
an interesting feature to have though... The best we can do is
create a class and define our own __str__ method.
> Here if I want to dynamically output floating data based
> on the number of significant digits (SD) from an input's:
> - If SD > m, truncate (or round it) in the output
> - If SD < m, just directly output the number
> (without padding 0 to the end).
> - In either of above cases, similar to %g, if %e is necessary,
> just output %e format as result
This lseems to be more about the number of SD input rather
than the actual precision of the stored data. In other words
this is a problem of string parsing.
I'd write a function that calculated the SD of a given string
and use the result to choose the output format. If you convert
the string to a float the precision and the number of SD will
be defined by Pythons internal binary representation which
may only be an approximation to the input value.
The output format can be defined by a set of parameters such as
sign,length,precision,style. Theese can be used to create a format
string:
fmt = "%%s%s.%s%s" % sign,length,precision,style
result = fmt % value
HTH,
Alan G.
More information about the Tutor
mailing list