andy-h
2/5/2014 - 6:41 PM

Functions to round a number to a specified precision (i.e., a specified number of decimal places).

Functions to round a number to a specified precision (i.e., a specified number of decimal places).

function roundToPrecision(num, precision){
	var shifter;
	precision = new Number(precision || 0);
	if(precision%1 !== 0) throw new RangeError("precision must be an integer");
	shifter = Math.pow(10, precision);
	return Math.round(num*shifter)/shifter;
}

function floorToPrecision(num, precision){
	var shifter;
	precision = new Number(precision || 0);
	if(precision%1 !== 0) throw new RangeError("precision must be an integer");
	shifter = Math.pow(10, precision);
	return Math.floor(num*shifter)/shifter;
}

function ceilToPrecision(num, precision){
	var shifter;
	precision = new Number(precision || 0);
	if(precision%1 !== 0) throw new RangeError("precision must be an integer");
	shifter = Math.pow(10, precision);
	return Math.ceil(num*shifter)/shifter;
}