Skip to content

Instantly share code, notes, and snippets.

@oliger
Created June 23, 2023 08:51
Show Gist options
  • Save oliger/1cb48f09cb7aa844c1b819527979d0c8 to your computer and use it in GitHub Desktop.
Save oliger/1cb48f09cb7aa844c1b819527979d0c8 to your computer and use it in GitHub Desktop.
Intl Parse Number
// https://observablehq.com/@mbostock/localized-number-parsing
const makeIntlParse = (locale: string) => {
const parts = new Map(new Intl.NumberFormat(locale).formatToParts(12345.6).map((part) => [part.type, part.value]));
const numerals = Array.from(new Intl.NumberFormat(locale, { useGrouping: false }).format(9876543210)).reverse();
const index = new Map(numerals.map((d, i) => [d, i]));
const reGroup = new RegExp(`[${parts.get("group")}]`, "g");
const reDecimal = new RegExp(`[${parts.get("decimal")}]`);
const reNumeral = new RegExp(`[${numerals.join("")}]`, "g");
return (str: string) => {
const parsedStr = str
.trim()
.replace(reGroup, "")
.replace(reDecimal, ".")
.replace(reNumeral, (d) => `${index.get(d)}`);
return parseFloat(parsedStr);
};
};
[
["fr", "12 345 678,9"],
["en", "12,345,678.90"],
["de", "12.345.678,90"],
["ar-EG", "١٢٬٣٤٥٬٦٧٨٫٩٠"],
].map(([locale, str]) => {
const parse = makeIntlParse(locale);
const result = parse(str);
console.log("locale: %s, str: %s, result: %f", locale, str, result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment