3

I have an input field that is formatted using .toLocaleString().

Then I need to use parseFloat() on that value to convert it to a number.

To do this with a US locale, I simply use value.replace(',','') to strip out the decimals before executing the parseFloat().

However this doesn't work in European locales in which the thousand separators and decimal points are inverted.

Is there a method of determining which locale your user is in and then whether to invert commas and decimals first?

Symphony0084
  • 1,257
  • 16
  • 33
  • Does this answer your question? [How can I parse a string with a comma thousand separator to a number?](https://stackoverflow.com/questions/11665884/how-can-i-parse-a-string-with-a-comma-thousand-separator-to-a-number) – James Coyle Jan 10 '20 at 09:38
  • can you provide some examples to understand it better – bajran Jan 10 '20 at 09:39
  • Does this answer your question? [Localization of input type number](https://stackoverflow.com/q/13412204/9434800) – Mickael B. Jan 10 '20 at 09:40
  • Unfortunately those other questions don't really address the issue, which is that the thousand separator could either be a comma or a decimal. @trincot's answer is a really good solution. – Symphony0084 Jan 10 '20 at 11:58

1 Answers1

9

You could use toLocaleString to first see how an example number is converted to string, then learn from that output what the locale's separators are, and use that info to parse the string:

function 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
trincot
  • 317,000
  • 35
  • 244
  • 286