Skip to content

Instantly share code, notes, and snippets.

@binaryhq
Created December 29, 2021 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binaryhq/591ebb718d3a143177ede86eae4735f1 to your computer and use it in GitHub Desktop.
Save binaryhq/591ebb718d3a143177ede86eae4735f1 to your computer and use it in GitHub Desktop.
localeParseFloat(s, locale) {
// Get the thousands and decimal separator characters used in the locale.
let [,thousandsSeparator,,,,decimalSeparator] = 1111.1.toLocaleString(locale);
// Remove thousand separators, and put a point where the decimal separator occurs
s = Array.from(s, c => c === thousandsSeparator ? ""
: c === decimalSeparator ? "." : c).join("");
// Now it can be parsed
return parseFloat(s);
}
console.log(parseFloat(localeParseFloat("1.100,9"))); // user's locale
console.log(parseFloat(localeParseFloat("1.100,9", "us"))); // US locale
console.log(parseFloat(localeParseFloat("1.100,9", "nl"))); // Dutch locale: reversed meaning of separators
// And the same but with separators switched:
console.log(parseFloat(localeParseFloat("1,100.9"))); // user's locale
console.log(parseFloat(localeParseFloat("1,100.9", "us"))); // US locale
console.log(parseFloat(localeParseFloat("1,100.9", "nl"))); // Dutch locale: reversed meaning of separators
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment