Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round up an integer to multiple of 3

I would like to round an integer up to its closest multiple of 3. Example:

var numberOne = 2
var numberTwo = 7
  • numberOne rounded up would equal 3
  • numberTwo rounded up would equal 9

I do not want it to ever round down.

Any ideas? Thanks

like image 656
Tom Coomer Avatar asked Nov 27 '14 20:11

Tom Coomer


People also ask

How do you round an integer?

Rounding to the Nearest IntegerIf the digit in the tenths place is less than 5, then round down, which means the units digit remains the same; if the digit in the tenths place is 5 or greater, then round up, which means you should increase the unit digit by one.

What is a multiple in rounding?

multiple is the multiple to use when rounding. The MROUND function rounds a number to the nearest multiple of the second argument. For example, in the above example, all retail prices have to be rounded to the nearest 5¢. To calculate the retail prices for all products we use this MROUND formula… =MROUND(C4,0.05)

How do you round to the nearest multiple?

You can use CEILING to round prices, times, instrument readings or any other numeric value. CEILING rounds up using the multiple supplied. You can use the MROUND function to round to the nearest multiple and the FLOOR function to round down to a multiple.


2 Answers

My 2 ct:

func roundUp(value: Int, divisor: Int) -> Int {
    let rem = value % divisor
    return rem == 0 ? value : value + divisor - rem
}
like image 148
Martin R Avatar answered Sep 18 '22 13:09

Martin R


I got this working in a Playground:

import Foundation

func roundToThree(value: Int) -> Int{
    var fractionNum = Double(value) / 3.0
    let roundedNum = Int(ceil(fractionNum))
    return roundedNum * 3
}

roundToThree(2)
roundToThree(7)
like image 44
erdekhayser Avatar answered Sep 19 '22 13:09

erdekhayser