How to convert double to int in swift
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)
.