Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there built-in custom numeric formatting in python?

Tags:

python

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.

like image 771
Xerion Avatar asked Apr 19 '26 02:04

Xerion


1 Answers

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).

like image 142
Alex Martelli Avatar answered Apr 21 '26 17:04

Alex Martelli