Skip to content


Format Currency in JavaScript

I went cruising around the web to find a good, easy way, to format a number into currency in JavaScript. No luck.

I took ideas from various places and this is what I came up with:


function numberToCurrency(number) {

    var currencySymbol     = '$';
    var thousandsSeparator = ',';

    number = stripDollarSign(number);
    number = isNaN(number) || number == '' || number == null ? 0.00 : number;
    var numberStr = parseFloat(number).toFixed(2).toString();
    var numberFormatted = new Array(numberStr.slice(-3));   // this returns the decimal and cents
    numberStr = numberStr.substring(0, numberStr.length-3); // this removes the decimal and cents
    /*
     * Why is there an `unshift()` function, but no `shift()`?
     * Also, a `pop()` function would be handy here.
     */
    while (numberStr.length > 3) {
        numberFormatted.unshift(numberStr.slice(-3)); // this prepends the last three digits to `numberFormatted`
        numberFormatted.unshift(thousandsSeparator); // this prepends the thousandsSeparator to `numberFormatted`
        numberStr = numberStr.substring(0, numberStr.length-3);  // this removes the last three digits
    }
    numberFormatted.unshift(numberStr); // there are less than three digits in numberStr, so prepend them
    numberFormatted.unshift(currencySymbol); // prepend the currencySymbol

    return numberFormatted.join(''); // put it all together
}

function stripDollarSign(s) {
    if (typeof s == 'string') { s = s.replace(/\$/g, ''); }
    return s;
}

I even created a unit test to make sure it functions as expected:

    testNumberToCurrency: function() { with(this) {
            assertEqual('$1.20', numberToCurrency(1.2));
            assertEqual('$1.20', numberToCurrency('1.2'));
            assertEqual('$1.20', numberToCurrency('1.202222'));
            assertEqual('$1.21', numberToCurrency('1.205555'));
            assertEqual('$1.20', numberToCurrency('$1.20'));
            assertEqual('$1.20', numberToCurrency('$1.2'));
            assertEqual('$1,000.20', numberToCurrency('$1000.2'));
            assertEqual('$10,000.20', numberToCurrency('$10000.2'));
            assertEqual('$100,000.20', numberToCurrency('$100000.2'));
            assertEqual('$1,000,000.20', numberToCurrency('$1000000.2'));
            assertEqual('$10,000,000.20', numberToCurrency('$10000000.2'));
    }}, 

Naturally this is a Scriptaculous Test.Unit.Runner test.

Posted in Javascript, Tips and Tricks.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.