Skip to content
Merged
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
14 changes: 14 additions & 0 deletions app/src/lib/__tests__/format.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,20 @@ describe('formatPercent', () => {
expect(formatPercent(-0.5)).toBe('\u22120.50%')
expect(formatPercent(0)).toBe('+0.00%')
})

it('舍入到 0 的负数不带减号,不出现「−0.00%」', () => {
// 回归:原实现先按原始值取符号再取绝对值格式化,
// -0.001 会得到「−0.00%」—— 符号和数字自相矛盾。
expect(formatPercent(-0.001)).toBe('+0.00%')
expect(formatPercent(-0.004, 2)).toBe('+0.00%')
expect(formatPercent(-0.04, 1)).toBe('+0.0%')
})

it('正负两侧的进位与符号一致', () => {
expect(formatPercent(0.004)).toBe('+0.00%')
expect(formatPercent(-0.006)).toBe('\u22120.01%')
expect(formatPercent(-1.005, 1)).toBe('\u22121.0%')
})
})

describe('trendOf', () => {
Expand Down
7 changes: 5 additions & 2 deletions app/src/lib/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,11 @@ export function formatShare(value: number, digits = 1): string {

/** 涨跌幅 3.852 -> "+3.85%";-0.5 -> "−0.50%"(用真正的减号,不是连字符) */
export function formatPercent(value: number, digits = 2): string {
const sign = value >= 0 ? '+' : '\u2212'
return `${sign}${Math.abs(value).toFixed(digits)}%`
const body = Math.abs(value).toFixed(digits)
// 符号要跟着「显示出来的数」走:-0.001 舍入后是 0.00,
// 再打减号就成了「−0.00%」,符号和数字自相矛盾。
const sign = value < 0 && Number(body) !== 0 ? '\u2212' : '+'
return `${sign}${body}%`
}

/**
Expand Down