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 = CGFl
While the other answers are correct, but the result you see will have trailing decimals.
For example:
let str = "3.141592654"
let foo = CGFloat((str as NSString).floatValue)
Result:
3.14159274101257
To get a proper value back from the string, try the following:
let str : String = "3.141592654"
let secStr : NSString = str as NSString
let flt : CGFloat = CGFloat(secStr.doubleValue)
Result:
3.141592654
Good question. There is not in fact any pure Swift API for converting a string that represents a CGFloat into a CGFloat. The only string-represented number that pure Swift lets you convert to a number is an integer. You'll have to use some other approach from some other library - for example, start with Foundation's NSString or C's (Darwin's) strtod
.
If you want a safe way to do this, here is a possibility:
let str = "32.4"
if let n = NSNumberFormatter().numberFromString(str) {
let f = CGFloat(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.
For Swift 3.0, I'd do something like this:
let str = "32.4"
guard let n = NSNumberFormatter().number(from: str) else { return }
// Use `n` here
In Swift 4, NSNumberFormatter
has been renamed to NumberFormatter
:
let str = "32.4"
guard let n = NumberFormatter().number(from: str) else { return }
in Swift 3.0
if let n = NumberFormatter().number(from: string) {
let f = CGFloat(n)
}
or this if you are sure that string meets all requirements
let n = CGFloat(NumberFormatter().number(from: string)!)
You should cast string
to double
and then cast from double
to CGFloat
, Let try this:
let fl: CGFloat = CGFloat((str as NSString).doubleValue)
Simple one line solution:
let pi = CGFloat(Double("3.14") ?? 0)