# 如何在 Python 中打印许多有效数字？

[英]How can I print many significant figures in Python?

``````>>> num = 0.0012345
``````

``````>>> f'{num:.3}'
'0.00123'
``````

``````>>> f'{num:.3f}'
'0.001'
``````

``````In [3]: val = 1./3

In [4]: print('%.15f' % val)
0.333333333333333
``````

`str.format()`

``````In [8]: print(str.format('{0:.15f}', val))
Out[8]: '0.333333333333333'
``````

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

``````>>> x = 1.23
>>> print("%.2g" % x)
1.2
>>> x = 12.3
>>> print("%.2g" % x)
12
``````

``````value = 10/3            #gives a float of 3.33333.....

print '%.15f' % value
print str.format('{0:.15f}', value)
``````

``````def nsf(num, n=1):
"""n-Significant Figures"""
numstr = ("{0:.%ie}" % (n-1)).format(num)
return float(numstr)
``````
1. 它首先使用指数表示法将数字转换为字符串
2. 然后将其作为float返回。

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