Javascript Cents to Money Display Function (with Commas)

Posted on November 01, 2013

The need for this comes up all the time so I thought I'd post my solution here. This converts currency as integer USD cents into dollars and cents with commas and a currency symbol.

// NOTE: does not work properly with values longer than
// single-digit trillions
Number.toMoney = function(cents){
    cents = parseFloat(cents) ? cents : 0.0;
    // place to two decimals then split off dollars and cents
    var components = (cents / 100).toFixed(2).toString().split(".");
    var decimal    = components[1];
    var dollars    = components[0] || "";
    var mod, remainder;
    var stringReverse = function(str){
        return str.split("").reverse().join("");
    };

    // do we need to worry about commas?
    if (dollars.length > 3){
        // since the commas are counted 3 characters from the
        // *right* we need to do some reversing
        dollars = stringReverse(dollars);

        // the match method used leaves off digits mod 3, so
        // we need to calculate what those omissions will be
        remainder = (mod = dollars.length % 3) ? stringReverse(dollars.slice(mod * -1)) + "," : "";

        // split every three characters, add commas, then add
        // omissions introduced by 'match' remainder back on
        dollars = remainder + stringReverse(dollars.match(/.../g).join(","));
    }

    // put it all together
    return ["$", [dollars, decimal].join(".")].join("");
}
comments powered by Disqus