Skip to content

Instantly share code, notes, and snippets.

@syrte
Last active July 5, 2016 16:31
Show Gist options
  • Save syrte/ccf0ff1a7745c2c4030a to your computer and use it in GitHub Desktop.
Save syrte/ccf0ff1a7745c2c4030a to your computer and use it in GitHub Desktop.
print required significant figures.
def siground(x, n):
from math import log10, floor
x, n = float(x), int(n)
assert n > 0
if x == 0:
return ("%%.%if" % (n - 1)) % x
m = 10 ** floor(log10(abs(x)))
x = round(x / m, n - 1) * m
p = floor(log10(abs(x)))
if -3 < p < n:
return ("%%.%if" % (n - 1 - p)) % x
else:
return ("%%.%ife%%+i" % (n - 1)) % (x / 10**p, p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment