//*** This code is copyright 2003 by Gavin Kistner, gavin@refinery.com //*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt //*** Reuse or modification is free provided you abide by the terms of that license. //*** (Including the first two lines above in your source code satisfies the conditions.) // Rounds a number to a specified number of decimals (optional) // Inserts the character of your choice as the thousands separator (optional) // Uses the character of your choice for the decimals separator (optional) // // It's not a highly optimized speed demon, but it gives the right result... // ...do you really care how speedy it is? :) Number.prototype.format=function(decimalPoints,thousandsSep,decimalSep){ var val=this+'',re1=/(?:\.\d+)?$/,re2=/^(-?)(\d+)/,x,y; if (decimalPoints!=null){ if (decimalPoints==0) val=Math.round(val)+''; else{ if ((y=decimalPoints-(x=(Math.round((x=re1.exec(val))[0]*Math.pow(10,decimalPoints))+'')).length)>0) x=Math.pow(10,y).toString().substring(1)+x; val=val.replace(re1,'.'+x); } } if (thousandsSep && (x=re2.exec(val))){ for (var a=x[2].split(''),i=a.length-3;i>0;i-=3) a.splice(i,0,thousandsSep); val=val.replace(re2,x[1]+a.join('')); } if (decimalSep) val=val.replace(/\./,decimalSep); return val; } // var x = 1234567.89532; // x.format() => 1234567.89532 // x.format(2) => 1234567.90 // x.format(2,',') => 1,234,567.90 // x.format(0,',') => 1,234,568 // x.format(null,',') => 1,234,567.89532 // x.format(null,' ',',') => 1 234 567,89532 // x.format(2,' ',',') => 1 234 567,90