Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions tests/test_fmt_tokens.py
Original file line number Diff line number Diff line change
@@ -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
11 changes: 7 additions & 4 deletions tokeneconomizer/plugin/accounting.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"