Skip to content

Instantly share code, notes, and snippets.

@stephenmm
Created March 4, 2022 23:52
Show Gist options
  • Save stephenmm/8e532c31cc5d657f548f5b55001c42bc to your computer and use it in GitHub Desktop.
Save stephenmm/8e532c31cc5d657f548f5b55001c42bc to your computer and use it in GitHub Desktop.
Finally got a engineering format the way I like it
from math import log10
def eng_str(x, significance=8, precision=3):
y = abs(x)
exponent = int(log10(y))
engr_exponent = exponent - exponent%3
z = y/10**engr_exponent
if x < 0:
z=z*-1
if engr_exponent > 0:
exp_str=f"+{engr_exponent:03}"
else:
exp_str=f"{engr_exponent:04}"
return f"{z:{significance}.{precision}f}"+f"e{exp_str}"
print(eng_str(.00001))
print(eng_str(-.00001))
print(eng_str(123456.2342))
print(eng_str(-.1))
# Output
# 10.000e-006
# -10.000e-006
# 123.456e+003
#-100.000e-003
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment