-
-
Save hello-alf/3a8271c0457f6b72c4ee 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