Reputation: 5574
var num = 1239128938213092131823;
num.toLocaleString('en-IN', { maximumSignificantDigits: 3, style: 'currency', currency: 'INR'});
on chrome:
on Firefox:
The Comma pattern output is different in both browsers. Firefox output is what i want and i need the same output in chrome also. Any fixes for this?
EDIT: Recently i checked this on Chrome Version 53.0.2785.116, now the chrome output is same as Firefox output.
Upvotes: 3
Views: 1823
Reputation: 31983
Updating my answer - my original statement that this was a bug is incorrect.
Updating again - found the reason for Chrome showing Rs.
The bug refers to something else since you are indeed passing a locale. Changing the locale to use Hindi as used in India (hi-IN
), I was able to get the following code to display the correctly formatted number on both browsers:
num.toLocaleString('hi-IN', {maximumSignificantDigits: 3, style: 'currency', currency: 'INR'});
However, you'll note that Chrome will display Rs.
instead of the Rupee symbol. 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.
To get some consistency, you can pass currencyDisplay: 'code'
as well, which will replace the Rupee symbol with "INR". This works fine on both Chrome and Firefox.
num.toLocaleString('hi-IN', {maximumSignificantDigits: 3, style: 'currency', currency: 'INR', currencyDisplay: 'code'});
You'll likely want to check if locale and/or Intl support is even available. That can be done with the following code from MDN (though as mentioned above, availability does not guarantee similar implementation):
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');
}
You should test that the function performs how you want on all browsers/devices, though it should work fine on all major, updated browsers.
Upvotes: 3