Skip to content

Instantly share code, notes, and snippets.

@MilesCranmer
Created July 1, 2022 20:35
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 MilesCranmer/142b6c3a4599aa428582301a6fc75eeb to your computer and use it in GitHub Desktop.
Save MilesCranmer/142b6c3a4599aa428582301a6fc75eeb to your computer and use it in GitHub Desktop.
Reduce precision of constants in a string
import re
def reduce_precision_of_constants_in_string(s, precision=3):
# Find all constants in the string:
constants = re.findall(r"\b[-+]?\d*\.\d+|\b[-+]?\d+\.?\d*", s)
for c in constants:
reduced_c = "{:.{precision}g}".format(float(c), precision=precision)
s = s.replace(c, reduced_c)
return s
s = "1.093840293 * exp(x1 * 0.00031823)"
print(reduce_precision_of_constants_in_string(s))
# >> '1.09 * exp(x1 * 0.000318)'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment