Round off a number to the next multiple of 5 using JavaScript
Given a positive integer n and the task is to round the number to the next whole number having divisible by 5.
Examples:
Input : 46 Output : 50 Input : 21 Output : 25 Input : 30 Output : 30
Approach 1:
- Take the number in a variable.
- Divide it by 5 and get the decimal value.
- Take the ceil value of the decimal value by using math.ceil().
- Multiply it by 5 to get the result.
<script> function round(x) { return Math.ceil(x / 5) * 5; } var n = 34; console.log(round(n)); </script> |
chevron_right
filter_none
Output:
35
Approach 2:
- Take the number in a variable.
- If it is divisible by 5, return the same number.
- Else divide it by 5, take floor value and again multiply it by 5 and add 5 as well.
<script> function round(x) { if (x % 5 == 0) { return int(Math.floor(x / 5)) * 5; } else { return (int(Math.floor(x / 5)) * 5) + 5; } } var n = 34; console.log(round(n)); </script> |
chevron_right
filter_none
Output:
35
Recommended Posts:
- Round off a number upto 2 decimal place using JavaScript
- JavaScript | Math.round( ) function
- JavaScript | Math.round( ) function
- JavaScript | Replace multiple strings with multiple other strings
- JavaScript | Split a string with multiple separators
- Create a string with multiple spaces in JavaScript
- JavaScript | Return multiple values from function
- How to remove multiple elements from array in JavaScript ?
- Call multiple JavaScript functions in onclick event
- How to disable scroll to change number in <input type="number"> field using JavaScript/jQuery?
- JavaScript | Number.MAX_VALUE & Number.MIN_VALUE with Examples
- How to convert a float number to the whole number in JavaScript?
- Number.isNaN() In JavaScript
- JavaScript | Number isSafeInteger()
- Javascript | Number() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.