How can I add a comma to separate each group of three digits in a text input field?

Viewed 12404

I have a text input field for a form where users are meant to enter a number. I would like to automatically insert a comma after every third digit.

For example, entering '20' would result in '20'. Entering '100' would result in '100'. But if they were to enter '1000', a comma would be inserted between the 1 and the following 0's (e.g., 1,000). Obviously this behaviour would continue should the number reach 7 digits (e.g., 1,000,000).

Is there an easy way to do this? I'm a bit of a newb at all of this, so please answer like you're talking to a child :)

10 Answers
var formatNumber = function(num, type) {
    var numSplit, int, dec, type;

    num = Math.abs(num);
    num = num.toFixed(2);

    numSplit = num.split('.')

    int = numSplit[0];
    if (int.length >= 3) {
        int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3);
    }

    dec = numSplit[1];

    return (type === 'exp'? sign = '-' : '+') + ' ' + int + '.' + dec;
};
Related