Round number up to the nearest multiple of 3

前端 未结 12 2020
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 08:39

Hay, how would i go about rounded a number up the nearest multiple of 3?

ie

25 would return 27
1 would return 3
0 would return 3
6 would return 6


        
相关标签:
12条回答
  • 2020-11-28 09:17

    $(document).ready(function() {
        var modulus = 3;
        for (i=0; i < 21; i++) {
            $("#results").append("<li>" + roundUp(i, modulus) + "</li>")
        }
    });
    
    
    function roundUp(number, modulus) {
        var remainder = number % modulus;
        if (remainder == 0) {
            return number;
        } else {
            return number + modulus - remainder;
        }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    Round up to nearest multiple of 3:
    <ul id="results">
    </ul>

    0 讨论(0)
  • 2020-11-28 09:19

    Here you are!

    Number.prototype.roundTo = function(num) {
        var resto = this%num;
        if (resto <= (num/2)) { 
            return this-resto;
        } else {
            return this+num-resto;
        }
    }
    

    Examples:

    y = 236.32;
    x = y.roundTo(10);
    
    // results in x = 240
    
    y = 236.32;
    x = y.roundTo(5);
    
    // results in x = 235
    
    0 讨论(0)
  • 2020-11-28 09:20

    Simply:

    3.0*Math.ceil(n/3.0)
    

    ?

    0 讨论(0)
  • 2020-11-28 09:21
    if(x%3==0)
        return x
    else
        return ((x/3|0)+1)*3
    
    0 讨论(0)
  • 2020-11-28 09:24
        if(n > 0)
            return Math.ceil(n/3.0) * 3;
        else if( n < 0)
            return Math.floor(n/3.0) * 3;
        else
            return 3;
    
    0 讨论(0)
  • 2020-11-28 09:25

    I'm answering this in psuedocode since I program mainly in SystemVerilog and Vera (ASIC HDL). % represents a modulus function.

    round_number_up_to_nearest_divisor = number + ((divisor - (number % divisor)) % divisor)
    

    This works in any case.

    The modulus of the number calculates the remainder, subtracting that from the divisor results in the number required to get to the next divisor multiple, then the "magic" occurs. You would think that it's good enough to have the single modulus function, but in the case where the number is an exact multiple of the divisor, it calculates an extra multiple. ie, 24 would return 27. The additional modulus protects against this by making the addition 0.

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