Prefixed provides an alternative implementation of the built-in float which supports formatted output with SI (decimal) and IEC (binary) prefixes.

>>> from prefixed import Float

>>> f'{Float(3250):.2h}'

>>> '{:.2h}s'.format(Float(.00001534))

>>> '{:.2j}B'.format(Float(42467328))

>>> f'{Float(2048):.2J}B'

Because prefixed.Float inherits from the built-in float, it behaves exactly the same in most cases.

Key differences:

  • When a math operation is performed with another real number type (float, int), the result will be a prefixed.Float instance.

  • Additional presentation types 'h', 'j', and 'J' are supported for f-strings and format().

    Type Meaning
    'h' SI format. Outputs the number with closest divisible SI prefix. (k, M, G, …)
    'j' IEC Format. Outputs the number with closest divisible IEC prefix. (Ki, Mi, Gi, …)
    'J' Short IEC Format. Same as 'j' but only a single character. (K, M, G, …)
  • When initializing from strings, SI and IEC prefixes are honored

>>> Float('2k')

>>> Float('2Ki')
  • An additional format flag ‘!’ is available which adds a space before the prefix
>>> f'{Float(3250):!.2h}'
'3.25 k'
  • An additional field, margin, can be specified which lowers or raises the threshold for for each prefix by the given percentage. Margin is specified before precision with the syntax %[-]digit+.
>>> f'{Float(950):.2h}'

>>> f'{Float(950):%-5.2h}'

>>> f'{Float(1000):%5.2h}'

>>> f'{Float(1050):%5.2h}'