prefixes

Convert numbers to scaled, prefixed values.

A unit prefix is a mnemonic that comes before a unit to indicate the multiples or fractions of the unit. For example, 0.0001 m becomes 100 µm using a metric prefix. 1024 become 1 ki using a binary prefix.

Example

Using a metric (base 10) prefix.

for n in [0, 1024, 10000, 10.5678e9, 0.1, .001234, 0.000835, 2.7e-9, ]:
    value, prefix = convert_to_prefix(n, UnitPrefix.Metric)
    print(f'{n}{value:.2f} {prefix}')
value, prefix = convert_to_prefix(12349)
print(f'{value:.0f} {prefix}m')

Output:

0 → 0.00
1024 → 1.02 k
10000 → 10.00 k
10567800000.0 → 10.57 G
0.1 → 100.00 m
0.001234 → 1.23 m
0.000835 → 835.00 µ
2.7e-09 → 2.70 n
12 km

Using a binary (base 2) prefix is very similar.

for n in [0, 1024, 100000, 9834298724398, 42795864723858438]:
    value, prefix = convert_to_prefix(n, UnitPrefix.Binary)
    print(f'{n}{value:.0f} {prefix}')

Output:

0 ⇒ 0
1024 ⇒ 1 Ki
100000 ⇒ 98 Ki
9834298724398 ⇒ 9 Ti
42795864723858438 ⇒ 38 Pi
class pymisclib.prefixes.UnitPrefix(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Prefix type used to indicate fractions or multiples of a unit.

For example, 1000 m can be expressed as 1 km using the metric prefix ‘kilo’ or ‘k’.

Binary = 1

Binary (base 2) prefix.

Metric = 2

Metric (base 10) prefix.

pymisclib.prefixes.convert_to_prefix(number: int | float, unit_prefix: UnitPrefix = UnitPrefix.Metric) tuple[float, str]

Convert a number to the nearest prefix.

The nearest prefix is the one with a non-zero digit before the decimal separator.

The valid range of the number depends on the prefix used.

Parameters:
  • number (int|float) – The value to convert.

  • unit_prefix (UnitPrefix) – The prefix type to use.

Returns:

Converted number and prefix.

Return type:

tuple[float, str]