How to convert double to int in swift

A more generic way to suppress (only) the .0 decimal place in a string representation of a Double value is to use NSNumberFormatter. It considers also the number format of the current locale.

let x : Double = 2.0
let doubleAsString = NumberFormatter.localizedString(from: (NSNumber(value: x), numberStyle: .decimal) 
// --> "2"

You can use:

Int(yourDoubleValue)

this will convert double to int.

or when you use String format use 0 instead of 1:

String(format: "%.0f", yourDoubleValue)

this will just display your Double value with no decimal places, without converted it to int.


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).

Tags:

Swift