How can you determine whether a double is an integ

2019-06-08 20:07发布

问题:

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

回答1:

extension Double {
    var isInt: Bool {
        let intValue = Int(self)
        return  Double(intValue) == self
    }
}

**Not working when value out of Int range.



回答2:

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


回答3:

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