I need to reformat numeric values based on the locale format, and to do this I use Number.toLocaleString("LOCAL")
function. In Iran, the majority of people prefer to use ,
as a thousands separator character, but Number.toLocaleString("fa-IR")
uses ٬
(Technically٬ it is correct).
Although you can replace the character by using the following code, is there any way to override the Number.toLocaleString("fa-IR")
's functionality?
function formatNumber(number) {
let string = number.toLocaleString('fa-IR'); // ۱۲٬۳۴۵٫۶۷۹
number = number.replace(/\٬/g, ",");
return string;
}
formatNumber(12345.6789); // the result: ۱۲,۳۴۵٫۶۷۹
PS: I know there are plenty of similar code-snippets out there, but I would like to override the built-in function (if possible).
If you're happy to change the prototype of Number
, then yes. It is often warned against changing the prototype of a built in class, as that could mess with other libraries and such.
Forging ahead regardless:
const old = Number.prototype.toLocaleString;
Number.prototype.toLocaleString = function(locale)
{
let result = old.call(this, locale);
if(locale === 'fa-IR')
{
result = result.replace(/\٬/g, ",");
}
return result;
}