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
func stringToFloat(value : String) -> Float { let numberFormatter = NumberFormatter() let number = numberFormatter. number(from: value) let numberFloatValue = number?. floatValue return numberFloatValue! }
Convert Swift String to DoubleUse Double , Float , CGFloat to convert floating-point values (real numbers). let lessPrecisePI = Float("3.14") let morePrecisePI = Double("3.1415926536") let width = CGFloat(Double("200.0")!)
The basic type for floating-point scalar values in Core Graphics and related frameworks.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With