Skip to content

Commit 34b602c

Browse files
committed
fix(shared): choose token units after rounding
1 parent cfafb4b commit 34b602c

2 files changed

Lines changed: 38 additions & 3 deletions

File tree

‎packages/shared/src/usageFormat.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,43 @@ import {
77
formatHourShort,
88
formatPercent,
99
formatRelativeHourShort,
10+
formatTokens,
1011
makeWindow,
1112
} from "./usageFormat.ts";
1213

14+
describe("formatTokens", () => {
15+
it.each([
16+
[999_499, "999K"],
17+
[999_500, "1M"],
18+
[999_999, "1M"],
19+
[999_499_999, "999M"],
20+
[999_500_000, "1B"],
21+
[999_999_999, "1B"],
22+
[999_499_999_999, "999B"],
23+
[999_500_000_000, "1T"],
24+
[999_999_999_999, "1T"],
25+
[-999_499, "-999K"],
26+
[-999_500, "-1M"],
27+
[-999_500_000, "-1B"],
28+
[-999_500_000_000, "-1T"],
29+
])("uses the rounded unit for %s tokens", (value, expected) => {
30+
expect(formatTokens(value)).toBe(expected);
31+
});
32+
33+
it.each([
34+
[0, "0"],
35+
[804, "804"],
36+
[999, "999"],
37+
[1_000, "1K"],
38+
[1_500_000, "1.50M"],
39+
[76_700_000, "76.7M"],
40+
[19_900_000_000, "19.9B"],
41+
[999_500_000_000_000, "1000T"],
42+
])("preserves existing formatting for %s tokens", (value, expected) => {
43+
expect(formatTokens(value)).toBe(expected);
44+
});
45+
});
46+
1347
describe("formatPercent", () => {
1448
it("distinguishes a small positive share from zero", () => {
1549
expect(formatPercent(0)).toBe("0.0%");

‎packages/shared/src/usageFormat.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,10 @@ export function formatCount(value: number): string {
2222

2323
export function formatTokens(value: number): string {
2424
const abs = Math.abs(value);
25-
if (abs >= 1e12) return `${trim(value / 1e12)}T`;
26-
if (abs >= 1e9) return `${trim(value / 1e9)}B`;
27-
if (abs >= 1e6) return `${trim(value / 1e6)}M`;
25+
// Choose the next suffix when three-digit rounding would otherwise produce 1000.
26+
if (abs >= 999_500_000_000) return `${trim(value / 1e12)}T`;
27+
if (abs >= 999_500_000) return `${trim(value / 1e9)}B`;
28+
if (abs >= 999_500) return `${trim(value / 1e6)}M`;
2829
if (abs >= 1e3) return `${trim(value / 1e3)}K`;
2930
return INTEGER.format(Math.round(value));
3031
}

0 commit comments

Comments
 (0)