diff --git a/frontend/src/utils/__tests__/formatMultiplier.spec.ts b/frontend/src/utils/__tests__/formatMultiplier.spec.ts new file mode 100644 index 0000000000..9c3b683085 --- /dev/null +++ b/frontend/src/utils/__tests__/formatMultiplier.spec.ts @@ -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') + }) +}) diff --git a/frontend/src/utils/formatters.ts b/frontend/src/utils/formatters.ts index ac56b28ffc..ebffa2e681 100644 --- a/frontend/src/utils/formatters.ts +++ b/frontend/src/utils/formatters.ts @@ -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') }