Javascript: round to the next multiple of 5

I need a utility function that takes an integer value (from 2 to 5 digits in length), which is rounded to next , multiplied by 5 instead of the next few of 5. Here's what I got:

function round5(x) { return (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5; } 

When I run round5(32) , it gives me 30 where I want 35.
When I run round5(37) , it gives me 35 , where I want 40.

When I run round5(132) , it gives me 130 , where I want 135.
When I run round5(137) , it gives me 135 where I want 140.

etc...

How to do it?

+93
javascript math rounding
Sep 23 '13 at 6:57
source share
7 answers

This will do the job:

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

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

+226
Sep 23 '13 at 7:03
source share

I came here looking for something like that. If my number is -0, -1, -2, it should be -0, and if it is -3, -4, -5, then it must be greater than -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 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 
+6
Sep 21 '17 at 8:34 on
source share

Like this?

 function roundup5(x) { return (x%5)?xx%5+5:x } 
+4
Sep 23 '13 at 7:05
source share
 voici 2 solutions possibles : y= (x % 10==0) ? x : xx%5 +5; //......... 15 => 20 ; 37 => 40 ; 41 => 45 ; 20 => 20 ; z= (x % 5==0) ? x : xx%5 +5; //......... 15 => 15 ; 37 => 40 ; 41 => 45 ; 20 => 20 ; 

Relationship Gender

+2
Mar 16 '16 at 9:27
source share

// round with precision

 var round = function (value, precision) { return Math.round(value * Math.pow(10, precision)) / Math.pow(10, precision); }; 

// round to 5 with precision

 var round5 = (value, precision) => { return round(value * 2, precision) / 2; } 
0
Jul 11 '18 at 11:43
source share
 const fn = _num =>{ return Math.round(_num)+ (5 -(Math.round(_num)%5)) } 

The reason for using the round is that the expected input may be a random number.

Thank!!!

0
Oct. 16 '18 at 10:14
source share
 if( x % 5 == 0 ) { return int( Math.floor( x / 5 ) ) * 5; } else { return ( int( Math.floor( x / 5 ) ) * 5 ) + 5; } 

may be?

-2
Sep 23 '13 at 7:03
source share



All Articles