Convert String to CGFloat in Swift

If you want a safe way to do this, here is a possibility:

let str = "32.4"
if let n = NumberFormatter().number(from: str) {
    let f = CGFloat(truncating: n)
}

If you change str to “bob”, it won’t get converted to a float, while most of the other answers will get turned into 0.0

Side note: remember also that decimal separator might be either comma or period. You might want to specify it inside the number formatter

let formatter = NumberFormatter()
formatter.decimalSeparator = "." // or ","

// use formatter (e.g. formatter.number(from:))

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)