Skip to content

Instantly share code, notes, and snippets.

@ekreutz
Created February 3, 2023 09:51
Show Gist options
  • Save ekreutz/8e31879f7849534ddceee0ffe38ced2a to your computer and use it in GitHub Desktop.
Save ekreutz/8e31879f7849534ddceee0ffe38ced2a to your computer and use it in GitHub Desktop.
Python - round a number to significant digits
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