Created
November 8, 2018 07:57
-
-
Save nawawi/e4e6010cdd64719bbb792f7a8748078a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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