Checking if a double value is an integer - Swift
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.
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