Convert String to Float in Swift

Stephen Fox picture Stephen Fox · Jun 6, 2014 · Viewed 133.6k times · Source

I'm trying to convert numbers taken from a UITextField, which I presume, are actually Strings, and convert them to Float, so I can multiply them.

I have two UITextfields which are declared as follows:

@IBOutlet var wage: UITextField
@IBOutlet var hour: UITextField

When the user presses a UIButton I want to calculate the wages the user earns, but I can't, as I need to convert them to floats first, before I can use them.

I know how to convert them to an integer by doing this:

var wageConversion:Int = 0
wageConversion = wage.text.toInt()!

However, I have no idea how to convert them to floats.

Answer

Firo picture Firo · Jun 6, 2014

Swift 2.0+

Now with Swift 2.0 you can just use Float(Wage.text) which returns a Float? type. More clear than the below solution which just returns 0.

If you want a 0 value for an invalid Float for some reason you can use Float(Wage.text) ?? 0 which will return 0 if it is not a valid Float.


Old Solution

The best way to handle this is direct casting:

var WageConversion = (Wage.text as NSString).floatValue

I actually created an extension to better use this too:

extension String {
    var floatValue: Float {
        return (self as NSString).floatValue
    }
}

Now you can just call var WageConversion = Wage.text.floatValue and allow the extension to handle the bridge for you!

This is a good implementation since it can handle actual floats (input with .) and will also help prevent the user from copying text into your input field (12p.34, or even 12.12.41).

Obviously, if Apple does add a floatValue to Swift this will throw an exception, but it may be nice in the mean time. If they do add it later, then all you need to do to modify your code is remove the extension and everything will work seamlessly, since you will already be calling .floatValue!

Also, variables and constants should start with a lower case (including IBOutlets)