Wednesday, September 3, 2025
HomeLanguagesJavascriptRound off a number to the next multiple of 5 using JavaScript

Round off a number to the next multiple of 5 using JavaScript

In this article, we are given a positive integer n and the task is to round the number to the next whole number divisible by 5.  There are various methods to Round off a number to the next multiple of 5 using JavaScript:

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.

Example:

javascript




<script>
    function round(x) {
        return Math.ceil(x / 5) * 5;
    }
      
    var n = 34;
    console.log(round(n));
</script>


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 the floor value and again multiply it by 5 and add 5 as well.

Example:

javascript




<script>
    function round(x) {
        if (x % 5 == 0) {
            return (Math.floor(x / 5)) * 5;
        } else {
            return ((Math.floor(x / 5)) * 5) + 5;
        }
    }
      
    var n = 34;
    console.log(round(n));
</script>


Output:

35
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6746 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS