【问题标题】:Using parseFloat() in different locales在不同的语言环境中使用 parseFloat()
【发布时间】:2020-01-10 18:24:11
【问题描述】:

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

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

要在美国语言环境中执行此操作,我只需使用 value.replace(',','') 在执行 parseFloat() 之前去除小数。

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

有没有一种方法可以确定您的用户所在的语言环境,然后是否先反转逗号和小数?

【问题讨论】:

标签: javascript locale


【解决方案1】:

您可以使用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

【讨论】:

  • 我非常喜欢这个解决方案。它不需要映射所有可能的语言环境并跟上它。
猜你喜欢
  • 2014-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多