Created
January 16, 2022 01:45
-
-
Save bocklund/fc89e7eeb371b01251add75431b2d7f1 to your computer and use it in GitHub Desktop.
Print floating point to n 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
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