Skip to content

Instantly share code, notes, and snippets.

@nash403
Created August 7, 2025 14:15
Show Gist options
  • Save nash403/416d20cacfb7dadd2e0b24c6f646ffa6 to your computer and use it in GitHub Desktop.
Save nash403/416d20cacfb7dadd2e0b24c6f646ffa6 to your computer and use it in GitHub Desktop.
Round a number in Javascript with specified number of decimals
function roundTo(n, digits) {
const factor = Math.pow(10, digits);
return Math.round(n * factor) / factor;
}
// roundTo(3.14159, 3); // 3.142
// roundTo(3.14159, 2); // 3.14
// roundTo(3.14159, 1); // 3.1
// roundTo(3.14159, 0); // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment