在不同的浏览器上提供不同的输出 [英] "toLocaleString" giving different output on different browsers

查看:28
本文介绍了在不同的浏览器上提供不同的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在铬上:

在Firefox上:

两个浏览器中的逗号模式输出不同。火狐输出是我想要的,我也需要相同的输出在Chrome中。有什么解决方法吗?

编辑: 最近我在Chrome版本53.0.2785.116上检查了一下,现在Chrome输出和Firefox输出是一样的。

推荐答案

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

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

该错误指的是其他内容,因为您确实是在传递区域设置。将区域设置更改为使用印度使用的印地语(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');
}

您应该测试该函数在所有浏览器/设备上的执行方式,尽管它应该可以在所有主要的更新浏览器上正常运行。

这篇关于在不同的浏览器上提供不同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆