Skip to content

Instantly share code, notes, and snippets.

@rougier
Created Jan 10, 2016
Embed
What would you like to do?
SI and IEC prefix for printing human readable numbers
# Copyright (c) 2016 Nicolas P. Rougier - BSD License
# SI prefixes as name:value
SI_prefix_name_value = {
"yocto": 10e-24, "zepto": 10e-21, "atto": 10e-18, "femto": 10e-15,
"pico": 10e-12, "nano": 10e-9, "micro": 10e-6, "milli": 10e-3,
"centi": 10e-2, "deci": 10e-1, "deca": 10e1, "hecto": 10e2,
"kilo": 10e3, "mega": 10e6, "giga": 10e9, "tera": 10e12,
"peta": 10e15, "exa": 10e18, "zetta": 10e21, "yotta": 10e24 }
# SI prefixes as name:symbol
SI_prefix_name_symbol = {
"yocto": "y", "zepto": "z", "atto": "a", "femto": "f",
"pico": "p", "nano": "n", "micro": "µ", "milli": "m",
"centi": "c", "deci": "d", "deca": "da", "hecto": "h",
"kilo": "k", "mega": "M", "giga": "G", "tera": "T",
"peta": "P", "exa": "E", "zetta": "Z", "yotta": "Y" }
# IEC prefixes as name:value
IEC_prefix_name_value = {
"kilo": 1024**1, "mega": 1024**2, "giga": 1024**3, "tera": 1024**4,
"peta": 1024**5, "exa": 1024**6, "zetta": 1024**7, "yotta": 1024**8 }
# IEC prefixes as name:symbol
IEC_prefix_name_symbol = {
"kilo": "k", "mega": "M", "giga": "G", "tera": "T",
"peta": "P", "exa": "E", "zetta": "Z", "yotta": "Y" }
unit = "micro"
prefix = SI_prefix_name_value[unit]
symbol = SI_prefix_name_symbol[unit]
value = 0.00042
print( "{:,}{:s}".format(round(value*10/prefix), symbol) )
value = 0.0042
print( "{:,}{:s}".format(round(value*10/prefix), symbol) )
unit = "kilo"
prefix = SI_prefix_name_value[unit]
symbol = SI_prefix_name_symbol[unit]
value = 1000
print( "{:,}{:s}".format(round(value*10/prefix), symbol) )
value = 65536
unit = "kilo"
prefix = IEC_prefix_name_value[unit]
symbol = IEC_prefix_name_symbol[unit]
print( "{:,}{:s}".format(round(value/prefix), symbol) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment