Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to round up to the nearest N in JavaScript
In JavaScript, rounding a number to the nearest multiple of N requires dividing by N, rounding the result, then multiplying back by N.
Consider this example:
const num = 76;
When rounding to different factors:
Round to nearest 10: 76 becomes 80
Round to nearest 100: 76 becomes 100
Round to nearest 1000: 76 becomes 0
We need a JavaScript function that takes a number and a rounding factor, returning the rounded result.
Syntax
const roundOffTo = (num, factor = 1) => {
const quotient = num / factor;
const res = Math.round(quotient) * factor;
return res;
};
Example
const num = 76;
const roundOffTo = (num, factor = 1) => {
const quotient = num / factor;
const res = Math.round(quotient) * factor;
return res;
};
console.log(roundOffTo(num, 10));
console.log(roundOffTo(num, 100));
console.log(roundOffTo(num, 1000));
Output
80 100 0
How It Works
The algorithm works in three steps:
-
Divide:
num / factorconverts the number to units of the factor -
Round:
Math.round()rounds to the nearest integer - Scale back: Multiply by the factor to get the final result
More Examples
// Round to nearest 5 console.log(roundOffTo(23, 5)); // 25 console.log(roundOffTo(22, 5)); // 20 // Round to nearest 50 console.log(roundOffTo(123, 50)); // 100 console.log(roundOffTo(175, 50)); // 200
25 20 100 200
Conclusion
To round to the nearest N, divide by N, apply Math.round(), then multiply by N. This technique works for any positive rounding factor.
Advertisements
