"的toLocaleString"在不同的浏览器上提供不同的输出

时间:2016-04-04 06:07:50

标签: javascript google-chrome firefox locale currency

var num = 1239128938213092131823;
num.toLocaleString('en-IN', { maximumSignificantDigits: 3, style: 'currency', currency: 'INR'});

on chrome:

enter image description here

Firefox上的

enter image description here

两种浏览器的逗号模式输出都不同。 Firefox输出是我想要的,我也需要在chrome中输出相同的输出。对此有何修复?

  

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

1 个答案:

答案 0 :(得分:3)

更新我的回答 - 我原来声明这是一个错误是不正确的。

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

的原因

由于您确实传递了区域设置,因此该bug会引用其他内容。将语言环境更改为使用印度语中使用的印地语(hi-IN),我能够获得以下代码以在两个浏览器上显示格式正确的数字:

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

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

  

使用“Rs。”而不是印度卢比标志(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');
}

您应该测试该功能是否能够在所有浏览器/设备上执行您想要的功能,但它应该适用于所有主要的更新浏览器。

相关问题