Skip to content

Commit 204c646

Browse files
phr4nkyNothingEverHappens
authored andcommitted
fix(common): normalize the exponent when rounding carries in exponential notation
Numbers with more than 22 integer digits are formatted in exponential notation with a single integer digit in the mantissa. When rounding to the requested number of fraction digits carried into a new digit, the carry was added to the mantissa instead of the exponent, e.g. `formatNumber(9.99999e22, 'en')` returned `10E+22` instead of `1E+23`. The same affected `formatPercent`, `formatCurrency` and the related pipes. Fold the carry into the exponent so the mantissa stays normalized. (cherry picked from commit 352aed3)
1 parent a6b5736 commit 204c646

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

‎packages/common/src/i18n/format_number.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -528,7 +528,16 @@ function roundNumber(parsedNumber: ParsedNumber, minFrac: number, maxFrac: numbe
528528
}, 0);
529529
if (carry) {
530530
digits.unshift(carry);
531-
parsedNumber.integerLen++;
531+
if (parsedNumber.exponent) {
532+
// In exponential notation the mantissa has a single integer digit. A carry out of it
533+
// (e.g. 9.99E+22 rounded to 10.0E+22) is folded into the exponent (1.00E+23) instead.
534+
// All digits after the carry are zeros here, so dropping the last one keeps the
535+
// number of fraction digits unchanged.
536+
digits.pop();
537+
parsedNumber.exponent++;
538+
} else {
539+
parsedNumber.integerLen++;
540+
}
532541
}
533542
}
534543

‎packages/common/test/i18n/format_number_spec.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,16 @@ describe('Format number', () => {
3838
expect(formatNumber(1e100, ɵDEFAULT_LOCALE_ID)).toEqual('1E+100');
3939
});
4040

41+
it('should normalize the exponent when rounding carries into a new digit', () => {
42+
expect(formatNumber(9.99999e22, ɵDEFAULT_LOCALE_ID)).toEqual('1E+23');
43+
expect(formatNumber(-9.99999e22, ɵDEFAULT_LOCALE_ID)).toEqual('-1E+23');
44+
expect(formatNumber(9.99999e22, ɵDEFAULT_LOCALE_ID, '1.2-2')).toEqual('1.00E+23');
45+
expect(formatNumber(9.9999e99, ɵDEFAULT_LOCALE_ID, '1.0-2')).toEqual('1E+100');
46+
expect(formatNumber(9.99999e22, ɵDEFAULT_LOCALE_ID, '1.0-10')).toEqual('9.99999E+22');
47+
expect(formatPercent(9.99999e22, ɵDEFAULT_LOCALE_ID)).toEqual('1E+25%');
48+
expect(formatCurrency(9.99999e22, ɵDEFAULT_LOCALE_ID, '$')).toEqual('$1.00E+23');
49+
});
50+
4151
it('should format NaN and Infinity with locale symbols', () => {
4252
expect(formatNumber(NaN, ɵDEFAULT_LOCALE_ID)).toEqual('NaN');
4353
expect(formatNumber(Infinity, ɵDEFAULT_LOCALE_ID)).toEqual('∞');

0 commit comments

Comments
 (0)