Skip to content

Commit f9b3886

Browse files
authored
fix(utils): return 0% for null and undefined values in formatpercentage (#91710)
- So far, the formatPercentage function returns `<0%` for `null` and `undefined` values; which is not correct in any way. - This PR explicitly returns 0% for those cases - this may not be semantically correct in some cases, so this PR also adds an option to define a null value. Follow-up to #91709
1 parent 9855231 commit f9b3886

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

static/app/utils/number/formatPercentage.spec.tsx

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,18 @@ describe('formatPercentage()', function () {
1616
expect(formatPercentage(-0.0001, 0, {minimumValue: 0.001})).toBe('<0.1%');
1717
expect(formatPercentage(0.00000234, 0, {minimumValue: 0.0001})).toBe('<0.01%');
1818
});
19+
20+
it('handles null and undefined inputs', function () {
21+
// @ts-expect-error we are testing invalid inputs
22+
expect(formatPercentage(null)).toBe('0%');
23+
// @ts-expect-error we are testing invalid inputs
24+
expect(formatPercentage(undefined)).toBe('0%');
25+
});
26+
27+
it('handles null and undefined inputs with a custom null value', function () {
28+
// @ts-expect-error we are testing invalid inputs
29+
expect(formatPercentage(null, 0, {nullValue: 'N/A'})).toBe('N/A');
30+
// @ts-expect-error we are testing invalid inputs
31+
expect(formatPercentage(undefined, 0, {nullValue: '-'})).toBe('-');
32+
});
1933
});

static/app/utils/number/formatPercentage.tsx

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,17 @@ export function formatPercentage(
99
places = 2,
1010
options: {
1111
minimumValue?: number;
12+
nullValue?: string;
1213
} = {}
1314
) {
1415
if (value === 0) {
1516
return '0%';
1617
}
1718

19+
if (value === undefined || value === null) {
20+
return options.nullValue ?? '0%';
21+
}
22+
1823
const minimumValue = options.minimumValue ?? 0;
1924

2025
if (Math.abs(value) <= minimumValue) {

0 commit comments

Comments
 (0)