Checking if a double value is an integer - Swift

There is now an Int(exactly:) initializer that will tell you this directly without the problem of out-of-range whole numbers.

if Int(exactly: self) != nil { ... }

This will only return a non-nil value if the result can actually be stored in Int exactly. There are many Double values that are "integers" but will not fit in an Int. (See MartinR's comment on the accepted answer.)


Swift 3

if dbl.truncatingRemainder(dividingBy: 1) == 0 {
  //it's an integer
}

Try 'flooring' the double value then checking if it is unchanged:

let dbl = 2.0
let isInteger = floor(dbl) == dbl // true

Fails if it is not an integer

let dbl = 2.4
let isInteger = floor(dbl) == dbl // false

check if % 1 is zero:

Swift 3:

let dbl = 2.0
let isInteger = dbl.truncatingRemainder(dividingBy: 1) == 0

Swift 2:

let dbl = 2.0
let isInteger = dbl % 1 == 0

Tags:

Double

Int

Swift