tags:

views:

71

answers:

2

in C#, I can do (#.####), which prints up to 4 significant digits after the decimal point. 1.2 -> 1.2 1.234 -> 1.234 1.23456789 -> 1.2345

Afaik, in python, there is only the c-style %.4f which will always print to 4 decimal points padded with 0s at the end if needed. I don't want those 0s.

Any suggestions for what is the cleanest way to achieve what I need?

One possible solution is to print it first and trim ending 0s myself, but hoping to find more clever ways.

+3  A: 

It looks like you can use the "g" format specifier for the .format() string function (only available in python 2.6+):

>>> x = 1.2
>>> print "{0:0.4g}".format(x)
1.2
>>> x = 1.234565789
>>> print "{0:0.4g}".format(x)
1.235

This includes digits before and after the decimal point, which is why you get 1.235 (rounded 1.2345 to 4 digits). If you only want significant digits to the right, you'd have to do something funny like

>>> x = 1.23456789
>>> # length of the number before the decimal
>>> left_sigdigs = len(str(x).partition(".")[0])
>>> format_string = "{0:0." + str(4 + left_sigdigs) + "g}"
>>> print format_string.format(x)
1.2346

Note that it still rounds, unlike your example.

Daniel G
+4  A: 

Large numbers would be formatted differently, but, for those you mention:

>>> for x in (1.2, 1.234, 1.23456789):
...   print '%.4g' % x
... 
1.2
1.234
1.235

This is the traditional equivalent (working in all versions of Python 2.whatever) of the more modern {0:0g}.format approach mentioned in @Daniel's answer (suitable only for Python 3.whatever and 2.6 or better). For example, if you're using Google App Engine (currently supporting Python 2.5, only), you need to use the %-operator approach to formatting (can't use the 2.6-or-better .format method).

Alex Martelli
Wonder if Google App Engine is going to be the new Red Hat Linux from Python's point of view... (Historical note for those asking WTF: Red Hat Linux only supported Python 1.5.6 for several consecutive releases, even when it was no longer actively developed and Python had gotten to 2.3 or so. If you wanted your Python code to run on stock RHL, you had to write to 1.5.6 as you couldn't expect 2.x to be installed. RHL eventually shipped Python 2.x before the time of the RHEL/Fedora split.)
Mike DeSimone
thanks Alex. too bad i can only vote 1 answer.
Xerion