Skip to content

Instantly share code, notes, and snippets.

@nawawi
Created November 8, 2018 07:57
Show Gist options
  • Save nawawi/e4e6010cdd64719bbb792f7a8748078a to your computer and use it in GitHub Desktop.
Save nawawi/e4e6010cdd64719bbb792f7a8748078a 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