Format number whilst being entered

Format decimal numbers with thousands grouping commas and decimal point whilst being entered

HTML

<input id="auto-format"
    placeholder="n,nnn,nnn.nnnnnn" 
    title="Enter a positive number, it will be correctly formatted"/>

JavaScript

Number.prototype.thousands = function () {
    var dp = (this.indexOf(".") + 1) ? "." : "";
    var chunks = this.replace(/[^\d\.]/g, "").split(".");
    return chunks[0].split("").reduce(groupThousands, []).join("").concat(dp, (chunks[1] || ""));
    function groupThousands(prev, digit, idx, digits) {
        if (!((digits.length - idx) % 3) && idx) prev.push(",");
        prev.push(digit);
        return prev;
    }
};
String.prototype.thousands = Number.prototype.thousands;

$(document).ready(function() {
    $("input.auto-format").on("input", autoFormat);
});

function autoFormat() {
    $(this).val($(this).val().thousands());
}