[removed] Round up to the next multiple of 5

后端 未结 8 926
[愿得一人]
[愿得一人] 2020-12-02 09:39

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

相关标签:
8条回答
  • 2020-12-02 09:55
    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
    
    0 讨论(0)
  • 2020-12-02 09:55

    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
    
    0 讨论(0)
  • 2020-12-02 09:55
    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!!!

    0 讨论(0)
  • 2020-12-02 10:01

    Like this?

    function roundup5(x) { return (x%5)?x-x%5+5:x }
    
    0 讨论(0)
  • 2020-12-02 10:12

    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.

    0 讨论(0)
  • 2020-12-02 10:13
    if( x % 5 == 0 ) {
        return int( Math.floor( x / 5 ) ) * 5;
    } else {
        return ( int( Math.floor( x / 5 ) ) * 5 ) + 5;
    }
    

    maybe?

    0 讨论(0)
提交回复
热议问题