fix(usage): keep significant decimals in cost tooltip rate multiplier

formatMultiplier rounded any value >= 0.01 with toFixed(2), so a
configured multiplier like 0.035 displayed as 0.04x in the /usage and
/admin/usage cost tooltips. Format with up to 4 decimals and trim
trailing zeros while keeping at least 2 decimals; display-only fix,
billing amounts were already computed from the true multiplier.
This commit is contained in:
shaw
2026-07-22 14:57:43 +08:00
parent cffea2979b
commit d0bdd7e771
2 changed files with 31 additions and 5 deletions
@@ -0,0 +1,27 @@
import { describe, expect, it } from 'vitest'
import { formatMultiplier } from '../formatters'
describe('formatMultiplier', () => {
it('keeps significant decimals instead of rounding to 2 places', () => {
expect(formatMultiplier(0.035)).toBe('0.035')
expect(formatMultiplier(0.125)).toBe('0.125')
expect(formatMultiplier(0.015)).toBe('0.015')
expect(formatMultiplier(0.0625)).toBe('0.0625')
})
it('pads to at least 2 decimals for round values', () => {
expect(formatMultiplier(0.3)).toBe('0.30')
expect(formatMultiplier(1)).toBe('1.00')
expect(formatMultiplier(1.5)).toBe('1.50')
expect(formatMultiplier(2)).toBe('2.00')
})
it('handles small values down to 4 decimals', () => {
expect(formatMultiplier(0.001)).toBe('0.001')
expect(formatMultiplier(0.0001)).toBe('0.0001')
})
it('falls back to 2 significant digits below 0.0001', () => {
expect(formatMultiplier(0.00005)).toBe('0.000050')
})
})
+4 -5
View File
@@ -8,11 +8,10 @@ export function formatCacheTokens(tokens: number): string {
}
/**
* 自适应精度格式化倍率(确保小数值如 0.001 不被截断)
* 自适应精度格式化倍率:保留至多 4 位小数并去掉末尾多余的 0,
* 但至少保留 2 位小数(0.035 -> "0.035",0.3 -> "0.30",1 -> "1.00")
*/
export function formatMultiplier(val: number): string {
if (val >= 0.01) return val.toFixed(2)
if (val >= 0.001) return val.toFixed(3)
if (val >= 0.0001) return val.toFixed(4)
return val.toPrecision(2)
if (val < 0.0001) return val.toPrecision(2)
return val.toFixed(4).replace(/(\.\d{2}\d*?)0+$/, '$1')
}