Skip to content

Instantly share code, notes, and snippets.

@jbryanscott
Created April 5, 2017 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jbryanscott/d06ad3555b9664b23dcddc3a84ba6761 to your computer and use it in GitHub Desktop.
Save jbryanscott/d06ad3555b9664b23dcddc3a84ba6761 to your computer and use it in GitHub Desktop.
Displaying proper significant figures in Python
from math import floor, log10
def display_sigfig(x, sigfigs=2) -> str:
'''
Suppose we want to show 2 significant figures. Implicitly we want to show 3 bits of information:
- The order of magnitude
- Significant digit #1
- Significant digit #2
'''
if sigfigs < 1:
raise Exception('Cannot have fewer than 1 significant figures. ({} given)'.format(sigfigs))
order_of_magnitude = floor(log10(abs(x)))
# Because we get one sigfig for free, to the left of the decimal
decimals = (sigfigs - 1)
x /= pow(10, order_of_magnitude)
x = round(x, decimals)
x *= pow(10, order_of_magnitude)
# Subtract from decimals the sigfigs we get from the order of magnitude
decimals -= order_of_magnitude
# But we can't have a negative number of decimals
decimals = max(0, decimals)
return '{:,.{dec}f}'.format(x, dec=decimals)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment