number formatting in javascript

demo

The thing to note is that the answer shown on the right is formatted with two digits on the right of the decimal point, and commas every third digit on the left.

The code that does that:

formatNumber=function(v,f){
	v=parseFloat(v);
	var l=Math.floor(f),a=v,c='',r=0;
	v=v.toFixed?v.toFixed((f-l)*10):v;
	while(a>=1){
		++r;
		a/=10;
	}
	for(;l>r;++r)c+='0';
	r=/(\d+)(\d{3})/;
	while(r.test(v))v=v.replace(r,'$1,$2');
	return v+c;
}

In the function, v is the value to format, and f is floating point digits – eg: .2 (10.23, 76.35), .3 (1.234, 8.200).

Comments are closed.

%d bloggers like this: