Convert String to CGFloat in Swift

I'm new to Swift, how can I convert a String to CGFloat?

I tried:

var fl: CGFloat = str as CGFloat
var fl: CGFloat = (CGFloat)str
var fl: CGFloat = CGFloat(str)

all didn't work


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

As of Swift 2.0, the Double type has a failable initializer that accepts a String. So the safest way to go from String to CGFloat is:

let string = "1.23456"
var cgFloat: CGFloat?

if let doubleValue = Double(string) {
    cgFloat = CGFloat(doubleValue)
}

// cgFloat will be nil if string cannot be converted

If you have to do this often, you can add an extension method to String:

extension String {

  func CGFloatValue() -> CGFloat? {
    guard let doubleValue = Double(self) else {
      return nil
    }

    return CGFloat(doubleValue)
  }
}

Note that you should return a CGFloat? since the operation can fail.


You should cast string to double and then cast from double to CGFloat, Let try this:

let fl: CGFloat = CGFloat((str as NSString).doubleValue)

This works:

let str = "3.141592654"
let fl = CGFloat((str as NSString).floatValue)