Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to CGFloat in Swift

Tags:

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

like image 896
Shai UI Avatar asked Dec 22 '14 02:12

Shai UI


People also ask

How to convert String value to Float in Swift?

func stringToFloat(value : String) -> Float { let numberFormatter = NumberFormatter() let number = numberFormatter. number(from: value) let numberFloatValue = number?. floatValue return numberFloatValue! }

How to convert String into Double iOS Swift?

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")!)

What is CGFloat in Swift?

The basic type for floating-point scalar values in Core Graphics and related frameworks.


2 Answers

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:)) 
like image 57
Gregory Higley Avatar answered Sep 22 '22 14:09

Gregory Higley


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.

like image 38
Michael McGuire Avatar answered Sep 18 '22 14:09

Michael McGuire