Skip to content

Instantly share code, notes, and snippets.

@KMurphs
Created October 26, 2021 13:36
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 KMurphs/4ce16cde334300841d7f51fe3aa3d8fd to your computer and use it in GitHub Desktop.
Save KMurphs/4ce16cde334300841d7f51fe3aa3d8fd to your computer and use it in GitHub Desktop.
A python function to convert a number to a string using SI Notation

Originally inspired by https://gist.github.com/cho45/9968462#gistcomment-3522694

import math
SI_PREFIXES_CENTER_INDEX = 8
si_prefixes = ('y', 'z', 'a', 'f', 'p', 'n', 'μ', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')


def to_si_notation(value: float, precision: int = 1):
    """Transforms a float number to a string (in SI Notation) using SI prefixes.
    ``e.g. 123456 => '123.46k'``

    Adapted from: https://gist.github.com/cho45/9968462 

    Args:
        value (float): The value to be converted
        precision (int, optional): The number of decimal places to display. Defaults to 1.

    Returns:
        str: String representing 'value' in SI Notation
    """

    value = float(value)
    if (value == 0): return str(value)

    exponent = math.floor(math.log10(abs(value)))
    exponent_of_1000 = (math.ceil if exponent < 0 else math.floor)(exponent / 3)
    if (exponent_of_1000 == 0): return "{0:.{1}f}".format(value, precision)
    
    mantissa = "{0:.{1}f}".format(float((value / math.pow(10, exponent_of_1000 * 3))), precision)
    si_prefix = si_prefixes[exponent_of_1000 + SI_PREFIXES_CENTER_INDEX]
    return f"{mantissa}{si_prefix}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment