13
Jan

Here is a quick JavaScript function that can be used to round numbers to any precision:

Usage:

var num = 8.3897086546;
alert(roundFloat(num, 2));
alert(roundFloat(num, 4));

Code:

/* JavaScript function to round off numbers */
function roundFloat(num, precision)
{
	if(num.toFixed)
	{
		num_round = num.toFixed(precision);
	}
	else
	{
		var tenths = 1;
		for( var i=0; i<precision; i++ )
		{
			tenths = tenths * 10;
		}
		num_round = Math.round(num*tenths)/tenths
	}
	if( isNaN(num_round) )
	{
		num_round = 0;
	}
	return num_round;
}

gayatri.sa
Posted by on 13 Jan 2009 by gayatri.sa in Javascript

Add reply

*