How to convert String to Double in Swift

In this tutorial, we will see how to convert String to Double in Swift.

A String is a sequence of characters, it can be numbers like “5.23” or “4.0”, letters, or a combination of both. The Double is a data type used to represent decimal numbers like 5.23, 4.0 or -7.1.

So, if we have a string “5.23” and we convert it to Double the result will be 5.23.

Now, follow the method below to convert String to Double

Using Double() initializer

We can use the Double() initializer to convert a numeric String into a Double. This initializer takes a parameter that will be converted into a Double.

The Double() initializer is a straightforward way to achieve this task.

Example

let stringValue = "5.23"
let doubleValue = Double(stringValue) ?? 0.0
print(doubleValue)

In the above program, I have declared the stringValue variable to store the numeric string value which is "5.23".

Then, I have passed the stringValue as a parameter to the Double() initializer to convert the value of  stringValue into a Double.

The ?? is used to provide a default value of 0.0 if the conversion fails.

Output:

5.23

Using NSNumberFormatter

We can also use NSNumberFormatter to convert string representations of numbers into their numerical values like converting "3.14" to Double.

This method was commonly used in older versions of Swift to convert strings to numbers.

Example

import Foundation

let stringValue = "5.23"
// Creating an instance of NumberFormatter
let formatter = NumberFormatter()
//To convert the string to a Double using the NumberFormatter
let doubleValue = formatter.number(from: stringValue)?.doubleValue ?? 0.0
print(doubleValue)

In the above code, I have used the NumberFormatter() to format and parse the number.

Then, the formatter.number(from: stringValue) will convert the string to an NSNumber. If the conversion is successful, .doubleValue will extract the Double value. And if the conversion fails the ?? is used to provide a default value of 0.0.

Output:

5.23

Using NSString

We can also convert String to Double using the NSString. This method provides a wide range of functionalities for handling strings, including tasks like string manipulation, comparison, searching, formatting, and conversion.

Example

import Foundation

let stringValue = "5.23"
// Convert the Swift String to an NSString, then convert it to a Double.
let doubleValue = (stringValue as NSString).doubleValue
print(doubleValue)

In the above code, I have used the (stringValue as NSString) to convert the Swift String to an NSString.

Then, when the String is converted to the NSString, I call the .doubleValue on the NSString to convert it to a Double.

Output:

5.23

Leave a Reply

Your email address will not be published. Required fields are marked *