[removed] Round up to the next multiple of 5

2019-01-07 10:10发布

问题:

I need a utility function that takes in an integer value (ranging from 2 to 5 digits in length) that rounds up to the next multiple of 5 instead of the nearest multiple of 5. Here is 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 do I do this?

回答1:

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.



回答2:

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


回答3:

Like this?

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


回答4:

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



回答5:

// 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;
}


回答6:

const fn = _num =>{
    return Math.round(_num)+ (5 -(Math.round(_num)%5))
}

reason for using round is that expected input can be a random number.

Thanks!!!



回答7:

if( x % 5 == 0 ) {
    return int( Math.floor( x / 5 ) ) * 5;
} else {
    return ( int( Math.floor( x / 5 ) ) * 5 ) + 5;
}

maybe?