Checking if a double value is an integer - Swift

后端 未结 12 2001
梦如初夏
梦如初夏 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:49

    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"]
    
    0 讨论(0)
  • 2020-12-14 14:50

    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
    
    }
    
    0 讨论(0)
  • 2020-12-14 14:51
    extension FloatingPoint {
        var isWholeNumber: Bool { isNormal ? self == rounded() : isZero }
    }
    
    let double = 3.0    
    double.isWholeNumber        // true
    print(3.15.isWholeNumber)   // false
    
    0 讨论(0)
  • 2020-12-14 14:54

    Using mod (%) won't work anymore.

    You can now use:

    let dbl = 2.0
    let isInteger = dbl.truncatingRemainder(dividingBy: 1.0) == 0.0
    
    0 讨论(0)
  • 2020-12-14 14:55

    Swift 3

    if dbl.truncatingRemainder(dividingBy: 1) == 0 {
      //it's an integer
    }
    
    0 讨论(0)
  • 2020-12-14 14:56

    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
    
    0 讨论(0)
提交回复
热议问题