Javascript &引用;toLocaleString“;在不同的浏览器上提供不同的输出
在chrome上: 在Firefox上: 两种浏览器中的逗号模式输出不同。Firefox输出是我想要的,我也需要chrome中的相同输出。有什么解决办法吗 编辑: 最近我在Chrome版本53.0.2785.116上检查了这个问题,现在Chrome输出与Firefox输出相同Javascript &引用;toLocaleString“;在不同的浏览器上提供不同的输出,javascript,google-chrome,firefox,locale,currency,Javascript,Google Chrome,Firefox,Locale,Currency,在chrome上: 在Firefox上: 两种浏览器中的逗号模式输出不同。Firefox输出是我想要的,我也需要chrome中的相同输出。有什么解决办法吗 编辑: 最近我在Chrome版本53.0.2785.116上检查了这个问题,现在Chrome输出与Firefox输出相同 更新我的答案-我最初认为这是一个bug的说法是不正确的 再次更新-找到Chrome显示Rs的原因。 这个bug指的是其他东西,因为您确实在传递区域设置。将区域设置更改为印度使用的印地语(hi in),我能够获得以下代码
更新我的答案-我最初认为这是一个bug的说法是不正确的 再次更新-找到Chrome显示
Rs的原因。
这个bug指的是其他东西,因为您确实在传递区域设置。将区域设置更改为印度使用的印地语(hi in
),我能够获得以下代码,以便在两种浏览器上显示格式正确的数字:
var num = 1239128938213092131823;
num.toLocaleString('en-IN', { maximumSignificantDigits: 3, style: 'currency', currency: 'INR'});
但是,您会注意到Chrome将显示Rs.
,而不是卢比符号:
使用“Rs.”代替印度卢比符号(U+20A8),其字体为
并非所有平台都提供支持
为了获得一致性,您还可以传递currencyDisplay:'code'
,它将卢比符号替换为“INR”。这在Chrome和Firefox上都能很好地工作
num.toLocaleString('hi-IN', {maximumSignificantDigits: 3, style: 'currency', currency: 'INR'});
您可能需要检查区域设置和/或支持是否可用。这可以通过实现(尽管如上所述,可用性并不保证类似的实现):
您应该测试该函数在所有浏览器/设备上的性能,尽管它在所有主要浏览器/设备上都可以正常工作,更新的浏览器。请注意,我已经更新了我的答案:它将为您提供一个基本正确的解决方案。请参阅我更新的答案:该解决方案完全正确-Chrome有一个内置的限制,不允许大量使用卢比符号hanks@Matthew@Matthew Firefox dev此处,您能在currencyDisplay不工作的地方提交一个bug或粘贴一些代码吗?toLocaleString('hi-IN',{maximumSignificantDigits:3,style:'currency',currency:'INR',currencyDisplay:'code'})适合我。谢谢你的好意。我没有意识到我在一台运行Firefox37的旧机器上测试。更新到45,一切正常。更新答案以反映这一点。:)感谢您的检查。@MatthewHerbst此问题现在已在最新的chrome中解决。
num.toLocaleString('hi-IN', {maximumSignificantDigits: 3, style: 'currency', currency: 'INR', currencyDisplay: 'code'});
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');
}