For a scientific application I need to output very precise numbers, so I have to print 15 significant figures. There are already questions on this topic here, but they all c
You could use the string formatting operator %
:
In [3]: val = 1./3
In [4]: print('%.15f' % val)
0.333333333333333
or str.format()
:
In [8]: print(str.format('{0:.15f}', val))
Out[8]: '0.333333333333333'
In new code, the latter is the preferred style, although the former is still widely used.
For more info, see the documentation.
Use these two common print idioms for formatting. Its a matter of personal taste on which is better.
value = 10/3 #gives a float of 3.33333.....
print '%.15f' % value
print str.format('{0:.15f}', value)
Personally I think the first is more compact and the 2nd is more explicit. Format has more features when working with multiple vals.
Let:
>>> num = 0.0012345
For 3 significant figures:
>>> f'{num:.3}'
'0.00123'
For 3 decimal places:
>>> f'{num:.3f}'
'0.001'
See the "presentation types for floating point and decimal" table at the bottom of this section for any additional requirements provided by e, E, f, F, g, G, n, %, None
.
To display N significant figures (not decimal places) you use the "g" format:
>>> x = 1.23
>>> print("%.2g" % x)
1.2
>>> x = 12.3
>>> print("%.2g" % x)
12
See format spec for details on precision:
The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with 'f' and 'F', or before and after the decimal point for a floating point value formatted with 'g' or 'G'. For non-number types the field indicates the maximum field size - in other words, how many characters will be used from the field content. The precision is not allowed for integer values.
You could use this function I wrote, it seems to be working fine and it's quite simple!:
def nsf(num, n=1):
"""n-Significant Figures"""
numstr = ("{0:.%ie}" % (n-1)).format(num)
return float(numstr)
Some tests:
>>> a = 2./3
>>> b = 1./3
>>> c = 3141592
>>> print(nsf(a))
0.7
>>> print(nsf(a, 3))
0.667
>>> print(nsf(-a, 3))
-0.667
>>> print(nsf(b, 4))
0.3333
>>> print(nsf(-b, 2))
-0.33
>>> print(nsf(c, 5))
3141600.0
>>> print(nsf(-c, 6))
-3141590.0
I hope this helps you ;)
Thought the original question wanted to format n significant figures, not n decimal points. So a custom function might be required until some more native built-in types are on offer? So you'll want something like:
def float_nsf(q,n):
"""
Truncate a float to n significant figures. May produce overflow in
very last decimal place when q < 1. This can be removed by an extra
formatted print.
Arguments:
q : a float
n : desired number of significant figures
Returns:
Float with only n s.f. and trailing zeros, but with a possible small overflow.
"""
sgn=np.sign(q)
q=abs(q)
n=int(np.log10(q/10.)) # Here you overwrite input n!
if q<1. :
val=q/(10**(n-1))
return sgn*int(val)*10.**(n-1)
else:
val=q/(10**n)
return sgn*int(val)*10.**n