Checking if a double value is an integer - Swift

后端 未结 12 2038
梦如初夏
梦如初夏 2020-12-14 14:18

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.         


        
12条回答
  •  情深已故
    2020-12-14 14:41

    How about converting the Double to an Int (which will cut off decimals), then back to a Double, then comparing this to the original Double? For example:

    var dbl:Double = 22/3
    dbl == Double(Int(dbl))
    // false: dbl = 7.33333... Double(Int(dbl)) = 7.0
    
    dbl = 25
    dbl == Double(Int(dbl))
    // true: dbl = 25.0, Double(Int(dbl)) = 25.0
    

提交回复
热议问题