How to convert double to int in swift

后端 未结 8 1767
别跟我提以往
别跟我提以往 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:03

    Swift 4 - Xcode 10

    Use this code to avoid a crash if the double value exceeds the int boundaries (and so isn't representable):

    Add this private extension to your class:

    private extension Int {
    
        init?(doubleVal: Double) {
            guard (doubleVal <= Double(Int.max).nextDown) && (doubleVal >= Double(Int.min).nextUp) else {
            return nil
        }
    
        self.init(doubleVal)
    }
    

    Use the extension in your class this way:

    func test() {
    
        let d = Double(123.564)
        guard let intVal = Int(doubleVal: d) else {
            print("cannot be converted")
        }
    
        print("converted: \(intVal)")
    }
    

提交回复
热议问题