Is there a built-in custom number formatting in python?

in C #, I can do (#. ####) that 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 c-style% .4f, which will always print up to 4 decimal places, filled with zeros at the end, if necessary. I do not want these 0s.

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

One possible solution is to print it first and crop the 0s ending, but hoping to find smarter ways.

+3
source share
3 answers

, "g" .format() ( 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

, 1.235 ( 1.2345 4 ). , - ,

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

, , .

+3

-, , :

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

( Python 2.whatever) {0:0g}.format, @Daniel ( Python 3. , 2.6 ). , Google App Engine ( Python 2.5), % -operator ( 2.6 t23).

+4
>>>x = 36.2215405525
>>>from decimal import Decimal
>>>print Decimal(str(x)).quantize(Decimal('0.0001'))
36.2215
0
source

Source: https://habr.com/ru/post/1764425/


All Articles