Skip to content

Instantly share code, notes, and snippets.

@wzul
Forked from nawawi/round.js
Created November 8, 2018 07:59
Show Gist options
  • Save wzul/aa735c5212c648395f0b8658d1347d31 to your computer and use it in GitHub Desktop.
Save wzul/aa735c5212c648395f0b8658d1347d31 to your computer and use it in GitHub Desktop.
function round(value, precision, mode) {
var m, f, isHalf, sgn;
precision |= 0;
m = Math.pow(10, precision);
value *= m;
sgn = (value > 0) | -(value < 0);
isHalf = value % 1 === 0.5 * sgn;
f = Math.floor(value);
if ( isHalf ) {
switch (mode) {
case 'PHP_ROUND_HALF_DOWN':
// rounds .5 toward zero
value = f + (sgn < 0);
break;
case 'PHP_ROUND_HALF_EVEN':
// rouds .5 towards the next even integer
value = f + (f % 2 * sgn);
break;
case 'PHP_ROUND_HALF_ODD':
// rounds .5 towards the next odd integer
value = f + !(f % 2);
break;
default:
// rounds .5 away from zero
value = f + (sgn > 0);
}
}
return ( isHalf ? value : Math.round(value) ) / m;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment