Created
December 29, 2021 05:49
-
-
Save binaryhq/591ebb718d3a143177ede86eae4735f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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