Round number up to the nearest multiple of 3

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

    As mentioned in a comment to the accepted answer, you can just use this:

    Math.ceil(x/3)*3
    

    (Even though it does not return 3 when x is 0, because that was likely a mistake by the OP.)

    Out of the nine answers posted before this one (that have not been deleted or that do not have such a low score that they are not visible to all users), only the ones by Dean Nicholson (excepting the issue with loss of significance) and beauburrier are correct. The accepted answer gives the wrong result for negative numbers and it adds an exception for 0 to account for what was likely a mistake by the OP. Two other answers round a number to the nearest multiple instead of always rounding up, one more gives the wrong result for negative numbers, and three more even give the wrong result for positive numbers.

提交回复
热议问题