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

"toLocaleString" giving different output on different browsers

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

在 chrome 上:

在 Firefox 上:

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

EDIT: Recently i checked this on Chrome Version 53.0.2785.116, now the chrome output is same as Firefox output.

正在更新我的回答 - 我原来说这是一个错误的说法是不正确的。

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

的原因

该错误指的是其他问题,因为您确实传递了语言环境。更改语言环境以使用印度使用的印地语 (hi-IN),我能够获得以下代码以在两种浏览器上显示正确格式的数字:

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

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

Use "Rs." instead of the Indian Rupee sign (U+20A8) for which the font support is not available on all platforms.

为了保持一致性,您也可以传递 currencyDisplay: 'code',这会将卢比符号替换为 "INR"。这在 Chrome 和 Firefox 上都能正常工作。

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

您可能想要检查区域设置是否 and/or Intl support is even available. That can be done with the 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');
}

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