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