Home

Javascript: Formatting Numbers

Posted by SteveHardie | On: Feb 03 2011

When rounding decimals, there are some built-in javascript functions that can help you with the basics

var num = 10;
var result = num.toFixed(2); // result will equal 10.00

num = 930.9805;
result = num.toFixed(3); // result will equal 930.981

num = 500.2349;
result = num.toPrecision(4);   // result will equal 500.2

num = 5000.2349;
result = num.toPrecision(4);   // result will equal 5000

num = 555.55;
result = num.toPrecision(2);   // result will equal 5.6e+2

Formatting with Commas
To add commas to a large number, there is no built in javascript function. The function below will add commas to a large number.

function formatNumber(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(d+)(d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

comment closed