How to Convert Strings into Double and Float Values Using Swift 2

Swift 4 Update notes below

In Swift 2, you get native support for working with different numeric types (Float, Double, and Int) and Strings. Prior to Swift 2, you had to do a lot of extra work to convert between types.

Swift 2 allows you to quickly change a String into a number (if it’s a valid conversion).

To convert, you need to use a new style, which is Apple’s recommended best practice.

Use the initializer for the type instead of the toInt() style that was available in Swift 1.2 and earlier.

Use Int and variants like Int32, UInt64, etc. to convert integer values.

var wholeNumber = Int("27")

Use Float or Double to convert floating-point values (real numbers).

let lessPrecisePI = Float("3.14")

let morePrecisePI = Double("3.1415926536")

These conversions can fail, which is why the Int(), Float(), and Double() initializers return an optional type (i.e.: Double?, Float?, Int?, etc.). If the value cannot be converted, the value will be nil.

let invalidNumber = Float("alphabet") // nil, not a valid number

To use the numbers, you need to unwrap them – I recommend using the if let syntax for user input from a UITextField (or you can try the new guard statement in Swift 2!).

if let cost = Double(textField.text!) {
    print("The user entered a value price of \(cost)")
} else {
    print("Not a valid number: \(textField.text!)")

You will need to unwrap the optional to get the value. The if let syntax above makes it safe to use cost if it’s a valid number, otherwise you can handle the invalid case (i.e.: “alphabet” is not a valid number, so it would become nil).

The new initializers for different value types have made Swift feel more unified – the simple conversions between types are a lot easier and straightforward. User input and JSON data parsing is much easier in Swift 2.

Convert Double, Float, or Int to String

If you want to convert any number to a String, you have a quick option and a (pretty) safe option. Use the String initializer to convert numbers into Strings.

var costString = String(9.99)
var ageString = String(18)

As long as the number isn’t optional, the resulting strings will be the String type, not a String? type.

Other Methods of Converting Numbers

Before Swift 2, you had to do extra work to convert Float and Double variables from the String type.

You may find code that uses the NSString initializer to get access to a doubleValue property, or the NSNumberFormatter to convert between String and numbers.

Swift 2 Code

var cost = ("9.99" as NSString).doubleValue  // invalid returns 0, not an optional. (not recommended)

// invalid returns an optional value (recommended)
var pi = NSNumberFormatter().numberFromString("3.14")?.doubleValue

Swift 4 Code

Apple has changed the NSNumberFormatter to NumberFormater, and during the API migration, the numberFromString() method is now number(from: String).

var pi = NumberFormatter().number(from: "3.14")?.doubleValue

The drawback to the NSString method is that it returns 0 when an invalid number string is used – you should always use the initializers described above or the NumberFormatter because they return optional values to show when the conversion fails.

I recommend that you make your code safer and use the NumberFormatter approach.

Build Your First iPhone App

Click here to learn how to create your first iPhone app design using Swift 4 with a polished user interface.