Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Round up to the next multiple of 5

People also ask

How do you round to the nearest multiple of 5 in JavaScript?

To round a number to the nearest 5, call the Math. round() function, passing it the number divided by 5 and multiply the result by 5 .

How do you round up to the next multiple?

You can use CEILING to round prices, times, instrument readings or any other numeric value. CEILING rounds up using the multiple supplied. You can use the MROUND function to round to the nearest multiple and the FLOOR function to round down to a multiple.

How do you round up in JavaScript?

ceil() The Math. ceil() function always rounds a number up to the next largest integer.

How do you make a number multiple of 5?

For finding the multiples of 5, we multiply 5 by 1, 5 by 2, 5 by 3, and so on and on. The multiples are the products of these multiplications. Some examples of multiples can be found below. In every given example, the counting numbers 1 through 8 is used.


This will do the work:

function round5(x)
{
    return Math.ceil(x/5)*5;
}

It's just a variation of the common rounding number to nearest multiple of x function Math.round(number/x)*x, but using .ceil instead of .round makes it always round up instead of down/up according to mathematical rules.


const roundToNearest5 = x => Math.round(x/5)*5

This will round the number to the nearest 5. To always round up to the nearest 5, use Math.ceil. Likewise, to always round down, use Math.floor instead of Math.round. You can then call this function like you would any other. For example,

roundToNearest5(21)

will return:

20

Like this?

function roundup5(x) { return (x%5)?x-x%5+5:x }

I arrived here while searching for something similar. If my number is —0, —1, —2 it should floor to —0, and if it's —3, —4, —5 it should ceil to —5.

I came up with this solution:

function round(x) { return x%5<3 ? (x%5===0 ? x : Math.floor(x/5)*5) : Math.ceil(x/5)*5 }

And the tests:

for (var x=40; x<51; x++) {
  console.log(x+"=>", x%5<3 ? (x%5===0 ? x : Math.floor(x/5)*5) : Math.ceil(x/5)*5)
}
// 40 => 40
// 41 => 40
// 42 => 40
// 43 => 45
// 44 => 45
// 45 => 45
// 46 => 45
// 47 => 45
// 48 => 50
// 49 => 50
// 50 => 50

voici 2 solutions possibles :
y= (x % 10==0) ? x : x-x%5 +5; //......... 15 => 20 ; 37 => 40 ;  41 => 45 ; 20 => 20 ; 

z= (x % 5==0) ? x : x-x%5 +5;  //......... 15 => 15 ; 37 => 40 ;  41 => 45 ; 20 => 20 ;

Regards Paul