Custom Number Formatter

Made by Adam Schwartz (http://polymath.mit.edu). Made for Stack Overflow question http://stackoverflow.com/questions/3328673/customize-jquery-mask-plug-in.

HTML

<input type="text" />
<div id='aaaa'>

</div>

JavaScript

$(function(){
    $('input').bind('keyup blur', function(){
        var i, j, final = '', input = $(this),
            raw = input.val().replace(/[^\d]/g, '');
        while (raw.substr(0, 1) === '0' && raw.length > 2) { //remove leading 0s for large numbers
            raw = raw.substr(1); 
        }
        while (raw.length < 2) { //pad with up to two 0s for small numbers
            raw = '0' + raw;
        }
        for (i = 1; i <= raw.length; i++) { //format the number as ##,###,###.##
            j = raw.length - i;
            final =
                (i === 2 ? '.' : ((i + 1) % 3) === 0 && i != raw.length ? ',' : '')
                + raw.substr(j, 1)
                + final;
        }
        input.val(final);
    });
});