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