Created
January 28, 2015 14:43
-
-
Save a-r-m-i-n/28647e735aa6efaba401 to your computer and use it in GitHub Desktop.
How to round correctly in JavaScript
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 sign(num) { | |
// IE does not support method sign here | |
if (typeof Math.sign === 'undefined') { | |
if (num > 0) { | |
return 1; | |
} | |
if (num < 0) { | |
return -1; | |
} | |
return 0; | |
} | |
return Math.sign(num); | |
} | |
function precise_round(num, decimals) { | |
var t=Math.pow(10, decimals); | |
return (Math.round((num * t) + (decimals>0?1:0)*(sign(num) * (10 / Math.pow(100, decimals)))) / t).toFixed(decimals); | |
} | |
precise_round(1.275, 2); // 1.28 | |
precise_round(0.035, 2); // 0.04 | |
precise_round(0.045, 2); // 0.05 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Killing is bad, instead use polyfills that load what is necessary on demand.