【问题标题】:"toLocaleString" giving different output on different browsers“toLocaleString”在不同的浏览器上给出不同的输出
【发布时间】:2016-04-04 06:07:49
【问题描述】:
var num = 1239128938213092131823;
num.toLocaleString('en-IN', { maximumSignificantDigits: 3, style: 'currency', currency: 'INR'});

在镀铬上:

在 Firefox 上:

两种浏览器的逗号模式输出不同。 Firefox 输出是我想要的,我也需要 chrome 中的相同输出。有什么解决办法吗?

编辑: 最近我在 Chrome 版本 53.0.2785.116 上检查了这个,现在 chrome 输出与 Firefox 输出相同。

【问题讨论】:

  • 请注意我已经更新了我的答案:它会给你一个最正确的解决方案。
  • 请查看我更新后的更新答案:该解决方案完全正确 - Chrome 对使用卢比符号有内置限制

标签: javascript google-chrome firefox locale currency


【解决方案1】:

更新我的答案 - 我最初关于这是一个错误的说法是不正确的。

再次更新 - 找到 Chrome 显示Rs.的原因

这个错误指的是别的东西,因为你确实传递了一个语言环境。更改语言环境以使用印度使用的印地语 (hi-IN),我能够获得以下代码以在两个浏览器上显示正确格式的数字:

num.toLocaleString('hi-IN', {maximumSignificantDigits: 3, style: 'currency', currency: 'INR'});

但是,您会注意到 Chrome 将显示 Rs. 而不是卢比符号。 This is an intentional decision by Chrome:

使用“卢比”。而不是印度卢比符号 (U+20A8) 的字体 并非所有平台都提供支持。

为了获得一些一致性,您也可以传递currencyDisplay: 'code',它将用“INR”替换卢比符号。这在 Chrome 和 Firefox 上都可以正常工作。

num.toLocaleString('hi-IN', {maximumSignificantDigits: 3, style: 'currency', currency: 'INR', currencyDisplay: 'code'});

您可能需要检查语言环境和/或Intl 支持是否可用。这可以通过following code from MDN 来完成(尽管如上所述,可用性并不能保证类似的实现):

function toLocaleStringSupportsLocales() {
  var number = 0;
  try {
    number.toLocaleString('i');
  } catch (e) {
    return e​.name === 'RangeError';
  }
  return false;
}

function toLocaleStringSupportsOptions() {
  return !!(typeof Intl == 'object' && Intl && typeof Intl.NumberFormat == 'function');
}

if(toLocaleStringSupportsLocales()) {
  if(toLocaleStringSupportsOptions()) {
    console.log(num.toLocaleString('hi-IN', {maximumSignificantDigits: 3, style: 'currency', currency: 'INR', currencyDisplay: 'code'}));
  } else {
   // Browser supports locales but does not support Intl options
   console.log(num.toLocaleString('hi-IN'));
  }
} else {
  // Browser does not support locales
  console.error('Cannot format number - locales not supported');
}

您应该测试该函数在所有浏览器/设备上的执行方式是否符合您的要求,尽管它应该在所有主要的更新浏览器上都能正常工作。

【讨论】:

  • 非常感谢@Matthew。
  • @Matthew Firefox 开发人员在这里,您能否提交错误或粘贴一些代码,其中 currencyDisplay 不起作用? (123.4).toLocaleString('hi-IN', {maximumSignificantDigits: 3, style: 'currency', currency: 'INR', currencyDisplay: 'code'}) 适合我。谢谢。
  • @evilpie 好电话。我没有意识到我正在运行 Firefox 37 的旧机器上进行测试。将其更新为 45 并且一切正常。答案已更新以反映这一点。 :)
  • 感谢您的检查。
  • @MatthewHerbst 这个问题现在在最新的 chrome 中得到了解决。
猜你喜欢
  • 1970-01-01
  • 2019-03-26
  • 2012-11-05
  • 1970-01-01
  • 2019-05-26
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
  • 2014-01-03
相关资源
最近更新 更多