Created
February 3, 2023 09:51
-
-
Save ekreutz/8e31879f7849534ddceee0ffe38ced2a to your computer and use it in GitHub Desktop.
Python - round a number to significant digits
This file contains 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 log10, floor | |
from decimal import Decimal as Dec | |
# Note: the method spec uses a union type float | Dec introduced in Python 3.10 | |
# Remove the type definitions to make it work with earlier versions. | |
def round_sd(x: float | Dec, sd: int = 3): | |
"""Round a value to a specified amount of significant digits `sd`. | |
""" | |
return round(x, sd - int(floor(log10(abs(x)))) - 1) | |
# | |
# Examples | |
# round_sd(1.01235, 3) -> 1.01 | |
# round_sd(-1.01235, 3) -> -1.01 | |
# round_sd(1670.0123, 3) -> 1670.0 | |
# round_sd(0.00000012345, 3) -> 1.23e-07 | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment