Created
August 7, 2025 14:15
-
-
Save nash403/416d20cacfb7dadd2e0b24c6f646ffa6 to your computer and use it in GitHub Desktop.
Round a number in Javascript with specified number of decimals
This file contains hidden or 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 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