Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Python format floats with certain amount of significant digits?

I want my Python (2.4.3) output numbers to have a certain format. Specifically, if the number is a terminating decimal with <= 6 significant digits, show it all. However, if it has > 6 significant digits, then output only 6 significant digits.

"A" shows how Python is writing the floats. "B" shows how I want them written. How can I make Python format my numbers in that way?

A: 10188469102.605597 5.5657188485 3.539 22.1522612479 0 15.9638450858 0.284024 7.58096703786 24.3469152383  B: 1.01885e+10 5.56572 3.539 22.1523 0 15.9638 0.284024 7.58097 24.3469 
like image 957
user1145925 Avatar asked Sep 11 '14 05:09

user1145925


People also ask

How do you print 3 sig figs in Python?

To print a number with a specific number of significant digits we do this: print '{0:1.3g}'. format(1./3.) print '{0:1.3g}'.

How do you print a float with 2 decimals in Python?

In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.


2 Answers

You'll want the g modifier for format that drops insignificant zeroes;

>>> "{0:.6g}".format(5.5657188485) '5.56572' >>> "{0:.6g}".format(3.539) '3.539' 

Sorry, my update also includes the fact that I am restricted to using Python 2.4.3, which does not have format() function.

The format specifiers work even without the .format() function:

>>> for i in a: ...    print '%.6g' % (i,) ... 1.01885e+10 5.56572 3.539 22.1523 0 15.9638 0.284024 7.58097 24.3469 
like image 158
Joachim Isaksson Avatar answered Sep 22 '22 05:09

Joachim Isaksson


There is a way to retain trailing zeros so that it consistently shows the number of significant digits. Not exactly what OP wanted, but probably useful to many.

a = [10188469102.605597,5.5657188485,3.539,22.1522612479,0,15.9638450858,0.284024,7.58096703786,24.3469152383]  for i in a:     print("{:#.6g}".format(i)) 

Output

1.01885e+10 5.56572 3.53900 22.1523 0.00000 15.9638 0.284024 7.58097 24.3469 

Note that this will only work with the format function and not with % operator.

According to the docs:

The '#' option causes the “alternate form” to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float, complex and Decimal types.

'g': General format ... insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the '#' option is used.

like image 20
jadelord Avatar answered Sep 19 '22 05:09

jadelord