Here's code that will format numbers to have commas in them, and it will guarantee 2 decimal points at the end, either by adding them or truncating to that amount. It will even work with numbers that already have commas in them.
**fixed to accomodate negative numbers**
Code:
var field = document.getElementById("idHere");
field.onblur = function(e) {
var w = this.value.replace(/[, ]/g, "");
if(isNaN(w*1)) {
alert("Please enter a number.");
return;
}
var d = ".00", v = "", s = false, p;
if((p=w.indexOf("."))!=-1) {
d = w.substring(p);
w = w.substring(0, p);
}
while(d.length<3) d += "0";
d = d.substring(0, 3);
if((p=w.charAt(0))=="+") w = w.substring(1);
else if(p=="-") {
w = w.substring(1);
s = true;
}
var n = w.length;
for(var i=0, j=n-1; i<n; ++i, --j) {
v += w.charAt(i);
if(j%3==0) v += ",";
}
this.value = (s? "-": "") + v.substring(0, v.length-1) + d;
}
Bookmarks