Skip to content

Instantly share code, notes, and snippets.

@ttamg
Last active June 9, 2022 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttamg/3f65227fd580b3d8dc8ba91e01507280 to your computer and use it in GitHub Desktop.
Save ttamg/3f65227fd580b3d8dc8ba91e01507280 to your computer and use it in GitHub Desktop.
Python function to round number to significant figures
from math import floor, log10
def sig_figs(x: float, precision: int):
"""
Rounds a number to number of significant figures
Parameters:
- x - the number to be rounded
- precision (integer) - the number of significant figures
Returns:
- float
"""
x = float(x)
precision = int(precision)
return round(x, -int(floor(log10(abs(x)))) + (precision - 1))
"""Examples"""
assert sig_figs(1346, 1) == 1000
assert sig_figs(1346, 3) == 1350
assert sig_figs(0.001346, 1) == 0.001
assert sig_figs(0.001346, 3) == 0.00135
"""
Other implementations of this covered in this Stack Overflow thread
https://stackoverflow.com/questions/3410976/how-to-round-a-number-to-significant-figures-in-python
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment