Follow @endyourif rss Facebook LinkedIn

Format Numbers as Currency with Javascript Format Numbers as Currency with Javascript

Published on Jun 12, 2022

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:

var number = 1233445.5678;
var formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });

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:

Number.prototype.currency = function(locale, isoCode) {
var formatter = new Intl.NumberFormat(locale, { style: 'currency', currency: isoCode });

return formatter.format(this);

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

Tags: JavaScript

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP