How can you determine whether a double is an integer?

泄露秘密 提交于 2019-12-08 12:39:32

问题


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


来源:https://stackoverflow.com/questions/42617928/how-can-you-determine-whether-a-double-is-an-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!