Skip to content

Instantly share code, notes, and snippets.

@bocklund
Created January 16, 2022 01:45
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 bocklund/fc89e7eeb371b01251add75431b2d7f1 to your computer and use it in GitHub Desktop.
Save bocklund/fc89e7eeb371b01251add75431b2d7f1 to your computer and use it in GitHub Desktop.
Print floating point to n significant digits
import math
def float_sigfigs(val, sigfigs):
"""Return a string representation of a floating point number rounded to some number of significant figures without scientific notation"""
rounded_val = float(f"{val:0.{sigfigs}g}")
num_digits = int(abs(math.log10(rounded_val))) + sigfigs
return f"{rounded_val:0.{num_digits}f}"
print(float_sigfigs(3.141592653589793e-20, 5)) # 0.000000000000000000031416
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment