Skip to content

Commit 746aafb

Browse files
committed
Add humanize.metric() for converting big/small numbers to SI units.
1 parent 43ebe21 commit 746aafb

3 files changed

Lines changed: 87 additions & 0 deletions

File tree

src/humanize/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
fractional,
99
intcomma,
1010
intword,
11+
metric,
1112
ordinal,
1213
scientific,
1314
)
@@ -38,6 +39,7 @@
3839
"fractional",
3940
"intcomma",
4041
"intword",
42+
"metric",
4143
"naturaldate",
4244
"naturalday",
4345
"naturaldelta",

src/humanize/number.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,3 +458,55 @@ def clamp(
458458
"Invalid format. Must be either a valid formatting string, or a function "
459459
"that accepts value and returns a string."
460460
)
461+
462+
463+
def metric(value: float, unit: str = "", precision: int = 3) -> str:
464+
"""Return a value with a metric SI unit-prefix appended.
465+
466+
Examples:
467+
```pycon
468+
>>> metric(1500, "V")
469+
'1.50kV'
470+
>>> metric(2e8, "W")
471+
'200MW'
472+
>>> metric(220e-6, "F")
473+
'220μF'
474+
>>> metric(1e-14, precision=4)
475+
'10.00f'
476+
477+
```
478+
479+
The unit prefix is always chosen so that non-significant zero digits are required.
480+
i.e. `123,000` will become `123k` instead of `0.123M` and `1,230,000` will become
481+
`1.23M` instead of `1230K`. For numbers that are either too huge or too tiny to
482+
represent without resorting to either leading or trailing zeroes, it falls back to
483+
`scientific()`.
484+
```pycon
485+
>>> metric(1e40)
486+
'1.00 x 10⁴⁰'
487+
488+
```
489+
490+
Args:
491+
value (int, float): Input number.
492+
unit (str): Optional base unit.
493+
precision (int): The number of digits the output should contain.
494+
495+
Returns:
496+
str:
497+
"""
498+
exponent = int(math.floor(math.log10(abs(value))))
499+
500+
if exponent >= 27 or exponent < -24:
501+
return scientific(value, precision - 1) + unit
502+
503+
value /= 10 ** (exponent // 3 * 3)
504+
if exponent >= 3:
505+
ordinal = "kMGTPEZY"[exponent // 3 - 1]
506+
elif exponent < 0:
507+
ordinal = "mμnpfazy"[(-exponent - 1) // 3]
508+
else:
509+
ordinal = ""
510+
value_ = format(value, ".%if" % (precision - (exponent % 3) - 1))
511+
512+
return f"{value_}{ordinal}{unit}"

tests/test_number.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,3 +181,36 @@ def test_scientific(test_args: list[typing.Any], expected: str) -> None:
181181
)
182182
def test_clamp(test_args: list[typing.Any], expected: str) -> None:
183183
assert humanize.clamp(*test_args) == expected
184+
185+
186+
@pytest.mark.parametrize(
187+
"test_args, expected",
188+
[
189+
([1, "Hz"], "1.00Hz"),
190+
([1.0, "W"], "1.00W"),
191+
([3, "C"], "3.00C"),
192+
([3, "W", 5], "3.0000W"),
193+
([1.23456], "1.23"),
194+
([12.3456], "12.3"),
195+
([123.456], "123"),
196+
([1234.56], "1.23k"),
197+
([12345, "", 6], "12.3450k"),
198+
([200_000], "200k"),
199+
([1e25, "m"], "10.0Ym"),
200+
([1e26, "m"], "100Ym"),
201+
([1e27, "A"], "1.00 x 10²⁷A"),
202+
([1.234e28, "A"], "1.23 x 10²⁸A"),
203+
([-1500, "V"], "-1.50kV"),
204+
([0.12], "120m"),
205+
([0.012], "12.0m"),
206+
([0.0012], "1.20m"),
207+
([0.00012], "120μ"),
208+
([1e-23], "10.0y"),
209+
([1e-24], "1.00y"),
210+
([1e-25], "1.00 x 10⁻²⁵"),
211+
([1e-26], "1.00 x 10⁻²⁶"),
212+
],
213+
ids=str,
214+
)
215+
def test_metric(test_args, expected):
216+
assert humanize.metric(*test_args) == expected

0 commit comments

Comments
 (0)