I would like to round an integer up to its closest multiple of 3. Example:
var numberOne = 2
var numberTwo = 7
I do not want it to ever round down.
Any ideas? Thanks
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.
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)
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.
My 2 ct:
func roundUp(value: Int, divisor: Int) -> Int {
let rem = value % divisor
return rem == 0 ? value : value + divisor - rem
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With