22

I need to check if an integer is divisible by another integer exactly.

If not I would like to round it up to the closest multiple of the number.

Example:

var numberOne = 3
var numberTwo = 5

numberTwo is not a multiple of numberOne therefore I would like it to round numberTwo up to 6.

How would I do this? Thank you

maxwell
  • 3,788
  • 6
  • 26
  • 40
Tom Coomer
  • 6,227
  • 12
  • 45
  • 82

4 Answers4

27

1) If you want to check or an integer is divided by another integer:

Swift 5

if numberOne.isMultiple(of: numberTwo) { ... }

Swift 4 or less

if numberOne % numberTwo == 0 { ... }

2) Function to round to the closest multiple value:

func roundToClosestMultipleNumber(_ numberOne: Int, _ numberTwo: Int) -> Int {
    var result: Int = numberOne
    
    if numberOne % numberTwo != 0 {
        if numberOne < numberTwo {
            result = numberTwo
        } else {
            result = (numberOne / numberTwo + 1) * numberTwo
        }
    }
    
    return result
}
maxwell
  • 3,788
  • 6
  • 26
  • 40
22

You can use the modulo operator %:

numberTwo % numberOne == 0

The modulo finds the remainder of an integer division between 2 numbers, so for example:

20 / 3 = 6
20 % 3 = 20 - 6 * 3 = 2

The result of 20/3 is 6.666667 - the dividend (20) minus the integer part of that division multiplied by the divisor (3 * 6) is the modulo (20 - 6 * 3) , equal to 2 in this case.

If the modulo is zero, then the dividend is a multiple of the divisor

More info about the modulo at this wikipedia page.

Antonio
  • 71,651
  • 11
  • 148
  • 165
  • The first part is working for me however I am not sure what the bottom line means. How do I work out what I should add to the 20 to make it divisible by 3? I would like to round it up. Thanks – Tom Coomer Nov 27 '14 at 18:10
  • Updated the answer - hope that explains a little bit. – Antonio Nov 27 '14 at 18:53
7

Swift 5

isMultiple(of:)

Returns true if this value is a multiple of the given value, and false otherwise.

func isMultiple(of other: Int) -> Bool

let rowNumber = 4

if rowNumber.isMultiple(of: 2) {
    print("Even")
} else {
    print("Odd")
}
Community
  • 1
  • 1
Saranjith
  • 11,242
  • 5
  • 69
  • 122
2

You can use truncatingRemainder. E.g.,

if number.truncatingRemainder(dividingBy: 10) == 0 {                
    print("number is divisible by 10")   
}
Lawliet
  • 3,438
  • 2
  • 17
  • 28