fix: \commaNumber\ silently returns '0' for NaN and falsy values (#427)
Replace truthiness guard with Number.isFinite() so NaN and Infinity are explicitly rejected rather than silently masked. Zero is now handled by toLocaleString, which returns '0' correctly. Add test cases for NaN and Infinity.
This commit is contained in:
parent
67c0ed953a
commit
04fbca939f
2 changed files with 11 additions and 2 deletions
|
|
@ -22,7 +22,8 @@ export function compactNumber(value: number): string {
|
||||||
|
|
||||||
/** Format number with commas (e.g. "1,234,567") */
|
/** Format number with commas (e.g. "1,234,567") */
|
||||||
export function commaNumber(value: number): string {
|
export function commaNumber(value: number): string {
|
||||||
return value ? value.toLocaleString('en-US') : '0';
|
if (!Number.isFinite(value)) return '0';
|
||||||
|
return value.toLocaleString('en-US');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Format a token amount with comma grouping and 2 decimal places (e.g. "1,234.56") */
|
/** Format a token amount with comma grouping and 2 decimal places (e.g. "1,234.56") */
|
||||||
|
|
|
||||||
|
|
@ -95,10 +95,18 @@ describe('compactNumber', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('commaNumber', () => {
|
describe('commaNumber', () => {
|
||||||
test('returns "0" for falsy input', () => {
|
test('returns "0" for zero', () => {
|
||||||
expect(commaNumber(0)).toBe('0');
|
expect(commaNumber(0)).toBe('0');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('returns "0" for NaN', () => {
|
||||||
|
expect(commaNumber(NaN)).toBe('0');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns "0" for Infinity', () => {
|
||||||
|
expect(commaNumber(Infinity)).toBe('0');
|
||||||
|
});
|
||||||
|
|
||||||
test('formats thousands with commas', () => {
|
test('formats thousands with commas', () => {
|
||||||
expect(commaNumber(1234)).toBe('1,234');
|
expect(commaNumber(1234)).toBe('1,234');
|
||||||
});
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue