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"