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