Skip to content

Instantly share code, notes, and snippets.

@10maurycy10
Last active April 1, 2021 03:03
Show Gist options
  • Save 10maurycy10/2f77bfd4721b08640e39b51ee87c54ca to your computer and use it in GitHub Desktop.
Save 10maurycy10/2f77bfd4721b08640e39b51ee87c54ca to your computer and use it in GitHub Desktop.
A quick and dirty way to format SI units.
import math
prefixes = [
("yotta",24),
("zetta",21),
("exa",18),
("peta",15),
("tera",12),
("giga",9),
("mega",6),
("kilo",3),
("",0),
("milli",-3),
("micro",-6),
("nano",-9),
("pico",-12),
("femto",-15),
("atto",-18),
("zepto",-21),
("yocto",-24)
]
def print_prefix(num,unit,sig_figs):
if num == 0:
return "0 " + unit
dec = int(math.log10(num))-1;
prefix = [i for i in prefixes if i[1]<=dec]
if len(prefix) == 0:
prefix = ("yocto",-24)
else:
prefix = prefix[0]
unrounded_mantissa = num/10**(prefix[1])
mantissa = round(unrounded_mantissa, sig_figs - int(math.floor(math.log10(abs(unrounded_mantissa)))) - 1)
return str(mantissa) + " " + prefix[0] + unit
#[print(print_prefix(2**(-i),"meters",3)) for i in range(40)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment