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.
The Swifty way:
let cals = [2.5, 2.0]
let r = cals.map{ return Int(exactly: $0) == nil ? "\($0)" : "\(Int($0))" }
r // ["2.5", "2"]
Simple Solution
I suggest converting the value to Int
then to Double
and checking the new value
if value == Double(Int(value)) {
// The value doesn't have decimal part. ex: 6.0
} else {
// The value has decimal part. ex: 6.3
}
extension FloatingPoint {
var isWholeNumber: Bool { isNormal ? self == rounded() : isZero }
}
let double = 3.0
double.isWholeNumber // true
print(3.15.isWholeNumber) // false
Using mod (%) won't work anymore.
You can now use:
let dbl = 2.0
let isInteger = dbl.truncatingRemainder(dividingBy: 1.0) == 0.0
Swift 3
if dbl.truncatingRemainder(dividingBy: 1) == 0 {
//it's an integer
}
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