diff --git a/tests/test_fmt_tokens.py b/tests/test_fmt_tokens.py new file mode 100644 index 00000000..8390aff6 --- /dev/null +++ b/tests/test_fmt_tokens.py @@ -0,0 +1,24 @@ +"""`te status` prints token figures as a person reads them (`accounting.fmt_tokens`): 512, 340.0k, +1.2M. A figure that rounds up to 1000 of its unit is one of the next unit: 999,950 tokens is +1.0M, not 1000.0k. Effective tokens are weighted, so they need not be whole: 999.6 is 1.0k.""" +import pytest + +from tokeneconomizer.plugin.accounting import fmt_tokens + + +@pytest.mark.parametrize("n, shown", [ + (None, "n/a"), (0, "0"), (512, "512"), (999, "999"), (999.4, "999"), + (1000, "1.0k"), (1049, "1.0k"), (340_000, "340.0k"), (999_949, "999.9k"), + (1_000_000, "1.0M"), (1_250_000, "1.2M"), (999_949_999, "999.9M"), + (1_000_000_000, "1.0B"), (2.5e12, "2500.0B"), (-1500, "-1.5k"), +]) +def test_a_token_figure_is_shown_in_its_unit(n, shown): + assert fmt_tokens(n) == shown + + +@pytest.mark.parametrize("n, shown", [ + (999.6, "1.0k"), (999_950, "1.0M"), (999_999, "1.0M"), + (999_950_000, "1.0B"), (999_999_999, "1.0B"), (-999_950, "-1.0M"), +]) +def test_a_figure_that_rounds_up_to_a_thousand_is_one_of_the_next_unit(n, shown): + assert fmt_tokens(n) == shown diff --git a/tokeneconomizer/plugin/accounting.py b/tokeneconomizer/plugin/accounting.py index 29bb2595..86b81b77 100644 --- a/tokeneconomizer/plugin/accounting.py +++ b/tokeneconomizer/plugin/accounting.py @@ -68,7 +68,10 @@ def fmt_tokens(n): if n is None: return "n/a" n = float(n) - for unit, div in (("B", 1e9), ("M", 1e6), ("k", 1e3)): - if abs(n) >= div: - return f"{n / div:.1f}{unit}" - return f"{n:.0f}" + units = (("", 1, 0), ("k", 1e3, 1), ("M", 1e6, 1), ("B", 1e9, 1)) + i = max((j for j, (_, div, _) in enumerate(units) if abs(n) >= div), default=0) + # A figure that rounds up to 1000 of its unit is one of the next: 999,950 is 1.0M, not 1000.0k. + while i < len(units) - 1 and abs(round(n / units[i][1], units[i][2])) >= 1000: + i += 1 + unit, div, places = units[i] + return f"{n / div:.{places}f}{unit}"