Round Half To Even With Javascript

Updated: v0.2.0 (special thanks to: Donatas (http://baubas.info)

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 places = 0;
	var strThis = this.toString();
	var orgPlaces = strThis.split('.').length > 1 ? strThis.split('.')[1].length : 0;
	var pToRnd = (parseFloat(placeToRound)).toFixed(orgPlaces);
	pToRnd < 1 ? places = pToRnd.toString().split('.')[1].length : places = 0;
	var decNum = (parseFloat(this)/pToRnd).toFixed(strThis.length);
	var floor = Math.floor(decNum);
	var dec = (decNum - floor).toFixed(strThis.length);
	parseFloat(this) > 0 ? floor = Math.floor(decNum) : floor = Math.ceil(decNum);
	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