Round number up to the nearest multiple of 3

前端 未结 12 2081
爱一瞬间的悲伤
爱一瞬间的悲伤 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:10

    This function will round up to the nearest multiple of whatever factor you provide. It will not round up 0 or numbers which are already multiples.

    round_up = function(x,factor){ return x - (x%factor) + (x%factor>0 && factor);}
    
    round_up(25,3)
    27
    round up(1,3)
    3
    round_up(0,3)
    0
    round_up(6,3)
    6
    

    The behavior for 0 is not what you asked for, but seems more consistent and useful this way. If you did want to round up 0 though, the following function would do that:

    round_up = function(x,factor){ return x - (x%factor) + ( (x%factor>0 || x==0) && factor);}
    
    round_up(25,3)
    27
    round up(1,3)
    3
    round_up(0,3)
    3
    round_up(6,3)
    6
    

提交回复
热议问题