You can use this function that I wrote, it works fine, and it is pretty simple !:
def nsf(num, n=1): """n-Significant Figures""" numstr = ("{0:.%ie}" % (n-1)).format(num) return float(numstr)
- First, it converts a number to a string using the exponent notation
- Then returns it as a float .
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
Hope this helps you;)
ionelberdin
source share