Python formatting formatting - like "g", but with lots of digits

I use "g" to format floating point values, but for me it changes scientific formatting too soon - on the 5th digit:

 >>> format(0.0001, "g") '0.0001' >>> format(0.00001, "g") '1e-05' 

This seems to be described in the "g" (-4) rules:

The exact rules are as follows: suppose that a result formatted with a representation type of 'e' and an accuracy of p-1 will have exp exp. Then, if -4 <= exp <p, the number is formatted with the representation type 'f' and precision p-1-exp. Otherwise, the number will be formatted with the representation type 'e' and precision p-1. In both cases, non-essential trailing zeros are removed from the value, and the decimal point is also deleted if there are no remaining digits after it.

Is there a way to display numbers like "g" , but with lots of numbers before switching to scientific notation?

I’m thinking of using ".6f" and stripping trailing zeros, but then I won’t be able to see small numbers that need scientific notation.

+4
source share
3 answers
 from math import log10 if log10(n) < -5: print "%e" % n else: print "%f" % n 

EDIT: it can also be put on one line:

 ("%e" if log10(n) < -5 else "%f") % n 

If n can be negative, use log10(abs(n)) instead of log10(n) .

EDIT 2: Improved based on Adal comments:

 "%e" % n if n and log10(abs(n)) < -5 else ("%f" % n).rstrip("0") 

This will print 0 as "0". If you want another representation like "0" or "0.0", you will need to make a special case with a separate if .

+3
source

If you are using Python 2.7, you can do the following using extended mini-language string formatting:

 >>> '{number:.{width}f}'.format(number=0.000000000001, width=20) '0.00000000000100000000' 

Then you can dynamically specify the desired value of number and width .

+3
source

I had the same question.

Looking at the Python documentation, it seems that g also supports precision values:

General format. For a given accuracy p> = 1, this rounds the number to p significant digits, and then formats the result in either fixed-point format or in scientific notation, depending on the value.

I do not know why other answers do not use this, and I am not very experienced in Python, but it works.

This can simply be achieved using format(0.00001, '.10g') , where 10 is the exact precision.

+2
source

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


All Articles