admin管理员组

文章数量:1287598

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 mas and decimals first?

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 mas and decimals first?

Share Improve this question asked Jan 10, 2020 at 9:33 Symphony0084Symphony0084 1,43521 silver badges37 bronze badges 4
  • Does this answer your question? How can I parse a string with a ma thousand separator to a number? – James Coyle Commented Jan 10, 2020 at 9:38
  • can you provide some examples to understand it better – bajran Commented Jan 10, 2020 at 9:39
  • Does this answer your question? Localization of input type number – Mickael B. Commented Jan 10, 2020 at 9:40
  • 1 Unfortunately those other questions don't really address the issue, which is that the thousand separator could either be a ma or a decimal. @trincot's answer is a really good solution. – Symphony0084 Commented Jan 10, 2020 at 11:58
Add a ment  | 

1 Answer 1

Reset to default 15

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(localeParseFloat("1.100,9")); // user's locale
console.log(localeParseFloat("1.100,9", "us")); // US locale
console.log(localeParseFloat("1.100,9", "nl")); // Dutch locale: reversed meaning of separators
// And the same but with separators switched:
console.log(localeParseFloat("1,100.9")); // user's locale
console.log(localeParseFloat("1,100.9", "us")); // US locale
console.log(localeParseFloat("1,100.9", "nl")); // Dutch locale: reversed meaning of separators

本文标签: javascriptUsing parseFloat() in different localesStack Overflow