Skip to main content

This JavaScript function will insert commas at the appropriate position for the specified currency value.

/**
 * Put Comma Values in Numbers
 *
 * This function assumes what is being submitted to it is a string, with a
 * decimal point and two places after the decimal.
 *
 * Then this function will properly comma separate the number. For example,
 * 2345643.00 will return 2,345,643.00
 *
 * @param {String} amount
 */
function CommaFormatted(amount) {
    var delimiter = ",";

    var a = amount.split('.', 2);
    var d = a[1];
    var i = parseInt(a[0], 10);

    if (isNaN(i)) {
        return '';
    }

    var minus = '';
    if (i < 0) {
        minus = '-';
    }

    i = Math.abs(i);
    var n = String(i);
    var a = [];

    while (n.length > 3) {
        var nn = n.substr(n.length - 3);
        a.unshift(nn);
        n = n.substr(0, n.length - 3);
    }

    if (n.length > 0) {
        a.unshift(n);
    }

    n = a.join(delimiter);

    if (d) {
        if (d.length < 1) {
            amount = n;
        }
        else {
            amount = n + '.' + d;
        }
    }
    else {
        amount = n + ".00"
    }

    amount = minus + amount;

    return amount;
}