更新我的答案 - 我最初关于这是一个错误的说法是不正确的。
再次更新 - 找到 Chrome 显示Rs.的原因
这个错误指的是别的东西,因为你确实传递了一个语言环境。更改语言环境以使用印度使用的印地语 (hi-IN),我能够获得以下代码以在两个浏览器上显示正确格式的数字:
num.toLocaleString('hi-IN', {maximumSignificantDigits: 3, style: 'currency', currency: 'INR'});
但是,您会注意到 Chrome 将显示 Rs. 而不是卢比符号。 This is an intentional decision by Chrome:
使用“卢比”。而不是印度卢比符号 (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');
}
您应该测试该函数在所有浏览器/设备上的执行方式是否符合您的要求,尽管它应该在所有主要的更新浏览器上都能正常工作。