ValueFormats: check for inf (#19376)

This commit is contained in:
Ryan McKinley 2019-09-25 00:04:51 -07:00 committed by Torkel Ödegaard
parent 94d7af888c
commit 32b73bb496
2 changed files with 14 additions and 0 deletions

View File

@ -1,6 +1,14 @@
import { toFixed, getValueFormat } from './valueFormats';
describe('valueFormats', () => {
describe('toFixed with edge cases', () => {
it('should handle non number input gracefully', () => {
expect(toFixed(NaN)).toBe('NaN');
expect(toFixed(Number.NEGATIVE_INFINITY)).toBe('-Inf');
expect(toFixed(Number.POSITIVE_INFINITY)).toBe('Inf');
});
});
describe('toFixed and negative decimals', () => {
it('should treat as zero decimals', () => {
const str = toFixed(186.123, -2);

View File

@ -33,6 +33,12 @@ export function toFixed(value: number, decimals?: DecimalCount): string {
if (value === null) {
return '';
}
if (value === Number.NEGATIVE_INFINITY) {
return '-Inf';
}
if (value === Number.POSITIVE_INFINITY) {
return 'Inf';
}
const factor = decimals ? Math.pow(10, Math.max(0, decimals)) : 1;
const formatted = String(Math.round(value * factor) / factor);