Checking if a double value is an integer - Swift

34,488

Solution 1

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

Solution 2

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

Solution 3

Swift 3

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

Solution 4

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.)

Solution 5

A small extension to check for this:

extension FloatingPoint {
    var isInt: Bool {
        return floor(self) == self
    }
}

Then just do

let anInt = 1.isInt
let nonInt = 3.142.isInt
Share:
34,488
Youssef Moawad
Author by

Youssef Moawad

I am the Founder of the software development group Uzusoft. Uzusoft is currently focused on making mobile apps for iOS (primary field) and Android. We currently have multiple apps on the Apple App Store which you can read about here. I have had a great passion for computers since I was 2 and started learning about programming since I was 9.

Updated on February 06, 2022

Comments

  • Youssef Moawad
    Youssef Moawad over 2 years

    I need to check if a double-defined variable is convertible to Int without losing its value. This doesn't work because they are of different types:

    if self.value == Int(self.value)
    

    where self.value is a double.