Is there anyway in Swift 3 to determine whether a double value has decimal places or not? In my program, I only want to perform a calculation to this double if it is an integer value. How can I check to see if there's non-zero numbers after the decimal point?
For example:
let double dx = 1.0 // This would return true
let double dy = 1.5 // This would return false
Any and all help is appreciated! Thanks,
Matthew
extension Double {
var isInt: Bool {
let intValue = Int(self)
return Double(intValue) == self
}
}
**Not working when value out of Int range.
Double
values will almost never be truly whole, they'll just be "close enough" according to some wholenessThreshold
. You can set this to your needs, and use it like so:
let dx = 1.0
let dy = 1.5
extension Double {
private static let wholenessThreshold = 0.01
var isWhole: Bool {
return abs(self - self.rounded()) < Double.wholenessThreshold
}
}
print(dx.isWhole) // true
print(dy.isWhole) // false
If the floor value of double equal to that double then it considered as Int otherwise it is Double.
let dx: Double = 1.0
let dy: Double = 1.5
let isInteger = floor(dx) == dx // return true
let isInteger = floor(dy) == dy // return false