Format Numbers as Currency with Javascript

F

If you’re using any sort of Javascript framework to dynamically create content, e.g. Loop a JavaScript array to build a table of data, at some point along the way you will have a value that needs to be formatted to a specific currency. To accomplish this I will leverage Javascript’s Intl.NumberFormat.

Let’s take a look at some code that will take a number and format it to a specific currency’s ISO format using Javascript:

[code]
var number = 1233445.5678;
var formatter = new Intl.NumberFormat(‘en-US’, { style: ‘currency’, currency: ‘USD’ });
console.log(formatter.format(number));
[/code]

The nice part about this function is that if you have ISO Codes you can instantiate the Intl.NumberFormat with your desired locale.

Now, to take this one step further to format numbers as currency using Javascript let’s extend the Number type and make it an extension method as follows:

[code]
Number.prototype.currency = function(locale, isoCode) {
var formatter = new Intl.NumberFormat(locale, { style: ‘currency’, currency: isoCode });

return formatter.format(this);
}
[/code]

This allow us to simplify the usage as follows:
console.log(number.currency(‘en-US’, ‘USD’));

About the author

By Jamie

My Books