在不同的语言环境中使用 parseFloat()

fam*_*oes 4 javascript locale

我有一个使用 格式化的输入字段.toLocaleString()

然后我需要使用parseFloat()该值将其转换为数字。

要在美国语言环境中执行此操作,我只需value.replace(',','')在执行parseFloat().

但是,这在千位分隔符和小数点颠倒的欧洲语言环境中不起作用。

有没有一种方法可以确定您的用户所在的区域设置,然后确定是否首先反转逗号和小数?

tri*_*cot 13

您可以toLocaleString首先查看示例数字如何转换为字符串,然后从该输出中了解区域设置的分隔符是什么,并使用该信息来解析字符串:

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
Run Code Online (Sandbox Code Playgroud)