Odd and Even numbers % does not work

So usually you can this here to compare Even and Odd numbers:


if checking % 2 == 0 {
                print("Even number")
            } else {
                print("Odd number")
            }


But I get this error and don't know what excactly to do:

'%' is unavailable: For floating point numbers use truncatingRemainder instead


Anyone an idea what to do? What is tuncatingRemainder ... ?


Thanks!

Accepted Reply

What is the type of checking ?


This works for Int


for Float or Double, you have to do as instructed

let checking = 4.0
if checking2.truncatingRemainder(dividingBy: 2) == 0 {
    print("Even number")
} else {
    print("Odd number")
}

Replies

What is the type of checking ?


This works for Int


for Float or Double, you have to do as instructed

let checking = 4.0
if checking2.truncatingRemainder(dividingBy: 2) == 0 {
    print("Even number")
} else {
    print("Odd number")
}

It is a double.

The way you wrote worked! Thanks!

While Claude31’s answer works in some situations, in the general case the concept of even and odd doesn’t make sense for floating point values. Once the magnitude of the floating point value exceeds that which can be represented exactly, the value starts dropping bits off the ‘bottom’, and it’s exactly this bottom bit that you need to determine whether something is even or odd.

Consider this:

func isEven(_ f: Float) -> Bool {
    f.truncatingRemainder(dividingBy: 2.0) == 0.0
}

let one: Float = 1.0
let two: Float = 2.0
let big: Float = 1_000_000_000

print(isEven(one))          // false
print(isEven(two))          // true
print(isEven(big))          // true
print(isEven(big + one))    // true!

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"