Polyfill inadequate Intl support

Ensure that formatting is balanced with parsing to avoid truncating numbers.
This commit is contained in:
Minh Nguyễn
2021-10-26 18:26:14 -07:00
parent 252828bb4b
commit 2ba7177080
5 changed files with 43 additions and 25 deletions
+11
View File
@@ -424,9 +424,20 @@ export function coreLocalizer() {
return code; // if not found, use the code
};
localizer.floatFormatter = (locale) => {
if (!('Intl' in window && 'NumberFormat' in Intl &&
'formatToParts' in Intl.NumberFormat.prototype)) {
return (number) => number.toString();
} else {
return (number) => number.toLocaleString(locale);
}
};
localizer.floatParser = (locale) => {
// https://stackoverflow.com/a/55366435/4585461
const polyfill = (string) => parseFloat(string, 10);
if (!('Intl' in window && 'NumberFormat' in Intl)) return polyfill;
const format = new Intl.NumberFormat(locale);
if (!('formatToParts' in format)) return polyfill;
const parts = format.formatToParts(12345.6);
const numerals = Array.from({ length: 10 }).map((_, i) => format.format(i));
const index = new Map(numerals.map((d, i) => [d, i]));