Kcko
5/24/2019 - 12:49 PM

JS - round, floor, ceil obj - Decimal precision

var DecimalPrecision = (function(){
	if (Number.EPSILON === undefined) {
		Number.EPSILON = Math.pow(2, -52);
	}
	this.round = function(n, p=2){
		let r = 0.5 * Number.EPSILON * n;
		let o = 1; while(p-- > 0) o *= 10;
		if(n < 0)
			o *= -1;
		return Math.round((n + r) * o) / o;
	}
	this.ceil = function(n, p=2){
		let r = 0.5 * Number.EPSILON * n;
		let o = 1; while(p-- > 0) o *= 10;
		if(n < 0)
			o *= -1;
		return Math.ceil((n + r) * o) / o;
	}
	this.floor = function(n, p=2){
		let r = 0.5 * Number.EPSILON * n;
		let o = 1; while(p-- > 0) o *= 10;
		if(n < 0)
			o *= -1;
		return Math.floor((n + r) * o) / o;
	}
	return this;
})();