Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python float formatting - like "g", but with more digits

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

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

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

The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4 <= exp < p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.

Is there a way to display numbers like "g", but with more digits 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, which need scientific notation.

like image 884
Meh Avatar asked Jan 07 '11 14:01

Meh


2 Answers

I had the same question.

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

General format. For a given precision 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 its magnitude.

I don't know, why the other answers don't use this and I am not very experienced in Python, but it works.

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

like image 129
clel Avatar answered Sep 25 '22 13:09

clel


from math import log10

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

EDIT: it's also possible to put it on a single line:

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

If n might be negative, then use log10(abs(n)) in place of log10(n).

EDIT 2: Improved based on Adal's 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'll need to special case it with a separate if.

like image 40
Thomas K Avatar answered Sep 24 '22 13:09

Thomas K