Formatting Currency with JavaScript

March 2009

Here's a nice little way to format decimal currencies in JavaScript, e.g. always display two decimal places and add commas to make larger numbers more readable.

It is hardly complex enough to warrant explanation but you can use it by calling the Currency() function below with two parameters: a currency symbol (e.g. $, £, €, ¥ etc.) and an amount.

A call of Currency("£", 17) will return £17.00, calling Currency("€", 1234567.89) will give you €1,234,567.89 (the string, not the cash, unfortunately).

function Currency(sSymbol, vValue) {
   aDigits = vValue.toFixed(2).split(".");
   aDigits[0] = aDigits[0].split("").reverse().join("").replace(/(\d{3})(?=\d)/g, "$1,").split("").reverse().join("");
   return sSymbol + aDigits.join(".");

With thanks to Chris Carline who thought of it first.

Jon Combe