Skip to content

Instantly share code, notes, and snippets.

@masautt
Created September 16, 2019 04:52
Show Gist options
  • Save masautt/2c83af1c919bf16f4dad21fe84d3f3aa to your computer and use it in GitHub Desktop.
Save masautt/2c83af1c919bf16f4dad21fe84d3f3aa to your computer and use it in GitHub Desktop.
How do you round numbers in JavaScript?
function roundUp(num, prec) {
prec = Math.pow(10, prec);
return Math.ceil(num * prec) / prec;
}
function roundDown(num, prec) {
prec = Math.pow(10, prec);
return Math.floor(num * prec) / prec;
}
// Built in Math function
console.log(Math.round(10.5)) // --> 11
// Custom Math Functions for Rounding Up/Down based on Precision
console.log(roundUp(1.85, 1)) // --> 1.9
console.log(roundDown(1.85, 1)) // --> 1.8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment