Skip to content

Commit 6c8576a

Browse files
fix(shared): token counts just below a unit boundary use the next unit
formatTokens picked the K/M/B/T suffix from the unrounded value, so 999,999 rounded to 1000K. Choose the unit after rounding instead. AI-assisted; verified with the tests and tools listed above.
1 parent d935fc8 commit 6c8576a

1 file changed

Lines changed: 11 additions & 6 deletions

File tree

‎packages/shared/src/usageFormat.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,18 @@ export function formatCount(value: number): string {
6363
return INTEGER.format(Math.round(value));
6464
}
6565

66+
const TOKEN_SUFFIXES = ["K", "M", "B", "T"] as const;
67+
6668
export function formatTokens(value: number): string {
67-
const abs = Math.abs(value);
68-
if (abs >= 1e12) return `${trim(value / 1e12)}T`;
69-
if (abs >= 1e9) return `${trim(value / 1e9)}B`;
70-
if (abs >= 1e6) return `${trim(value / 1e6)}M`;
71-
if (abs >= 1e3) return `${trim(value / 1e3)}K`;
72-
return INTEGER.format(Math.round(value));
69+
if (Math.abs(Math.round(value)) < 1e3) return INTEGER.format(Math.round(value));
70+
let scaled = value / 1e3;
71+
let unit = 0;
72+
// Choose the unit after rounding, so 999,999 reads 1M rather than 1000K.
73+
while (Math.abs(Number(trim(scaled))) >= 1e3 && unit < TOKEN_SUFFIXES.length - 1) {
74+
scaled /= 1e3;
75+
unit += 1;
76+
}
77+
return `${trim(scaled)}${TOKEN_SUFFIXES[unit]}`;
7378
}
7479

7580
function trim(value: number): string {

0 commit comments

Comments
 (0)