views:

272

answers:

2

How to format a float so it does not containt the remaing zeros? In other words, I want the resulting string to be as short as possible..?

Like:

3 -> "3"
3. -> "3"
3.1 -> "3.1"
3.14 -> "3.14"
3.140 -> "3.14"
+2  A: 

You could use %g to achieve this:

'%g'%(3.140)

or, for Python 2.6 or better:

'{0:g}'.format(3.140)

From the docs for format: g causes (among other things)

insignificant trailing zeros [to be] removed from the significand, and the decimal point is also removed if there are no remaining digits following it.

unutbu
Oh, almost! Sometimes it formats the float in scientific notation ("2.342E+09") - is it possible to turn it off, i.e. always show all significant digits?
TarGz
+2  A: 

Me, I'd do ('%f' % x).rstrip('0').rstrip('.') -- guarantees fixed-point formatting rather than scientific notation, etc etc. Yeah, not as slick and elegant as %g, but, it works (and I don't know how to force %g to never use scientific notation;-).

Alex Martelli
Thanks it works exactly like I wanted! Just a tiny bit unfortunate there is no presentation type for this kind of behaviour....
TarGz
@TarGz, agreed, it would surely be more elegant to have some %-flags for that. For modern Python's approach see http://docs.python.org/library/string.html?highlight=string#string-formatting -- but it seems to behave, in regard to your specific problem, just like `'%g' % x` used to, it just has arguably nicer syntax. Plus, you can now subclass `string.Formatter` to do your own customizations.
Alex Martelli