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

标签 javascript google-chrome firefox locale currency

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

在 Chrome 上:

enter image description here

在 Firefox 上:

enter image description here

两种浏览器的逗号模式输出不同。 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'});

您可能需要检查语言环境和/或 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');
}

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

关于javascript - "toLocaleString"在不同的浏览器上给出不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36395577/

相关文章:

html - 当鼠标悬停在链接上时如何显示图像

firefox - 如何在 Firefox 中为 HTML 元素的溢出文本显示省略号?

javascript - Firefox 选项卡顺序打开

javascript - 如何在 jQuery ajax post 中传递动态数据量

javascript - Fabric.js - 无法动态设置属性

javascript - Typescript 可以声明语言特性吗?例如; `!variable` 为 `no variable`

html - 从 Chrome 打印出来的内容不居中

javascript - 将 JQuery 代码添加到主网站后,它无法在 Google Chrome 中运行

javascript - 什么可能阻止 Javascript 将值存储在剪贴板上?

javascript - CORS 和 Angular header 身份验证的烦人问题