Round Half To Even With Javascript

The following script provides an easy way to perform unbiased rounding, convergent rounding, statistician’s rounding, Dutch rounding, Gaussian rounding, or bankers’ rounding using Javascript.

Examples

var numToRound = 10.005;
document.write(numToRound.rhte(0.01);
result: 10.00

var numToRound = 10.0015;
document.write(numToRound.rhte(0.001);
result: 10.002

var numToRound = 10.00500000001;
document.write(numToRound.rhte(0.01);
result: 10.01

var numToRound = 1005001;
document.write(numToRound.rhte(10000);
result: 1010000

/*
	Round Half To Even (rhte) extends the 'Number' and 'String' objects

	Argument(placeToRound) examples: 0.0001,0.01,1,10,100

	Usage:
		Number.rhte(rounding value)
			(124.34450000).rhte(0.001) - [Result: 124.344]
			(124.34450001).rhte(0.001) - [Result: 124.345]
			(124.34550000).rhte(0.001) - [Result: 124.346]

		String.rhte(rounding value)
			'124.34450000'.rhte(0.001) - [Result: 124.344]
			'124.34450001'.rhte(0.001) - [Result: 124.345]
			'124.34550000'.rhte(0.001) - [Result: 124.346]
*/
function rhte(placeToRound){
	var pToRnd = parseFloat(placeToRound);
	var decNum = parseFloat(this)/pToRnd;
	var floor = Math.floor(decNum);
	var dec = decNum - floor;
	var floor,oddEven,places;
	parseFloat(this) > 0 ? floor = Math.floor(decNum) : floor = Math.ceil(decNum);
	pToRnd < 1 ? places = pToRnd.toString().split('.')[1].length : places = 0;
	floor % 2 == 1 ? oddEven = 1 : oddEven = 0;
	if(dec != 0.5){
		return ((Math.round(decNum)) * pToRnd).toFixed(places);
	}
	else{
		if(oddEven == 1){
			return ((floor + 1) * pToRnd).toFixed(places);
		}
		else{
			return (floor * pToRnd).toFixed(places);
		}
	}
}

Number.prototype.rhte = rhte;
String.prototype.rhte = rhte;

Leave a Reply