Last active
June 9, 2022 15:49
-
-
Save ttamg/3f65227fd580b3d8dc8ba91e01507280 to your computer and use it in GitHub Desktop.
Python function to round number to significant figures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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