libb.format

format(value, style)[source]

Format a numeric value with various formatting options.

Supports commas, parens for negative values, and special cases for zeros.

Parameters:
  • value – Numeric value to format.

  • style (str) – Format specification string.

Returns:

Formatted string.

Return type:

str

Style format: n[cpzZkKmMbBsS%#]/[kmb] (e.g., '2c', '0cpz', '1%', '1s')

  • n - number of decimals

  • c - use commas

  • p - wrap negative numbers in parenthesis

  • z - use a ‘ ‘ for zero values

  • Z - use a ‘-’ for zero values

  • K/k - convert to thousands and add ‘K’ suffix

  • M/m - convert to millions and add ‘M’ suffix

  • B/b - convert to billions and add ‘B’ suffix

  • S/s - convert to shorter of KMB formats

  • % - scale by 100 and add a percent sign at the end (unless z/Z)

  • # - scale by 10000 and add ‘bps’ at the end

  • /x - divide the number by 1e3 (k), 1e6 (m), 1e9 (b) first (does not append the units like KMB do)

Example:

>>> format(1234.56, '2c')
'1,234.56'
>>> format(-100, '0cp')
'(100)'
>>> format(0, '2z')
''
>>> format(0.5, '1%')
'50.0%'
>>> format(1500000, '1M')
'1.5M'