Skip to content

Instantly share code, notes, and snippets.

@a-r-m-i-n
Created January 28, 2015 14:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save a-r-m-i-n/28647e735aa6efaba401 to your computer and use it in GitHub Desktop.
Save a-r-m-i-n/28647e735aa6efaba401 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
@MiguelQueiroz
Copy link

Thank you for this improvement. But we shall let IE die...

@workguy66
Copy link

Killing is bad, instead use polyfills that load what is necessary on demand.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment