How to convert double to int in swift

后端 未结 8 1702
别跟我提以往
别跟我提以往 2020-12-24 10:30

So I\'m trying to figure out how I can get my program to lose the .0 after an integer when I don\'t need the any decimal places.

@IBOutlet weak var numberOf         


        
相关标签:
8条回答
  • 2020-12-24 11:05

    It is better to verify a size of Double value before you convert it otherwise it could crash.

    extension Double {
        func toInt() -> Int? {
            if self >= Double(Int.min) && self < Double(Int.max) {
                return Int(self)
            } else {
                return nil
            }
        }
    }
    

    The crash is easy to demonstrate, just use Int(Double.greatestFiniteMagnitude).

    0 讨论(0)
  • 2020-12-24 11:06

    These answers really don't take into account the limitations of expressing Int.max and Int.min that Doubles have. Ints are 64 bit but Doubles only have 52 bits of precision in their mantissa.

    A better answer is:

    extension Double {
        func toInt() -> Int? {
            guard (self <= Double(Int.max).nextDown) && (self >= Double(Int.min).nextUp) else {
                return nil
            }
    
            return Int(self)
        }
    }
    
    0 讨论(0)
提交回复
热议问题