'Check if an integer is divisible by another integer (Swift)

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



Solution 1:[1]

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.

Solution 2:[2]

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
}

Solution 3:[3]

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")
}

Solution 4:[4]

You can use truncatingRemainder. E.g.,

if number.truncatingRemainder(dividingBy: 10) == 0 {                
    print("number is divisible by 10")   
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Community
Solution 4 Lawliet