Skip to content

Instantly share code, notes, and snippets.

@hello-alf
Forked from a-r-m-i-n/precise_round.js
Created October 1, 2015 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hello-alf/3a8271c0457f6b72c4ee to your computer and use it in GitHub Desktop.
Save hello-alf/3a8271c0457f6b72c4ee to your computer and use it in GitHub Desktop.
How to round correctly in JavaScript
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