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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With