Skip to content

Instantly share code, notes, and snippets.

@abudden
Created October 16, 2023 06:06
Show Gist options
  • Save abudden/3252252632bd8271c49c886771d8f82d to your computer and use it in GitHub Desktop.
Save abudden/3252252632bd8271c49c886771d8f82d to your computer and use it in GitHub Desktop.
Engineering format function
import math
def format_eng(number, places=2, force_exponent=None, use_si=False, use_unicode=False, use_latex=False, return_components=False, strip_zeros=True, unit=None, pos_sign=False):
si_lookup = {
24: 'Y', 21: 'Z',
18: 'E', 15: 'P', 12: 'T',
9: 'G', 6: 'M', 3: 'k',
-3: 'm', -6: 'μ', -9: 'n',
-12: 'p', -15: 'f', -18: 'a',
-21: 'z', -24: 'y',
}
if number == 0:
result = "%.*f" % (places, 0)
if '.' in result and strip_zeros:
result = result.rstrip('0').rstrip('.')
if unit is not None:
result += " " + unit
return result
abs_value = abs(number)
exponent = int(math.log10(abs_value))
engr_exponent = exponent - (exponent % 3)
if force_exponent is not None:
engr_exponent = force_exponent
value = abs_value / (10**engr_exponent)
if value < 1.0 and force_exponent is None:
value *= 1000.0
engr_exponent -= 3
if number > 0 and pos_sign:
sign = '+'
elif number < 0:
sign = '-'
else:
sign = ''
if sign == '-' and use_unicode:
sign = '–' # en-dash
elif sign == '-' and use_latex:
sign = '$-$'
if return_components:
return sign, value, engr_exponent
else:
result = "%s%.*f" % (sign, places, value)
if '.' in result and strip_zeros:
result = result.rstrip('0').rstrip('.')
if engr_exponent != 0:
if use_si and engr_exponent in si_lookup:
result += ' %s' % (si_lookup[engr_exponent])
if use_latex and 'μ' in result:
result = result.replace('μ', '$\mathrm{\mu}$')
elif use_unicode:
result += '×10' + ''.join(dict(zip("-0123456789", "⁻⁰¹²³⁴⁵⁶⁷⁸⁹")).get(c, c) for c in "%d" % engr_exponent)
elif use_latex:
result += r'$\times 10^{%d}$' % (engr_exponent)
else:
result += 'e%d' % (engr_exponent)
if unit is not None:
if ' ' not in result:
result += ' '
result += unit
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment