Swift: Converting String to Double

Converting a string to double is easy in Swift.

(swiftString as NSString).doubleValue

does the trick.

The following example just works fine

But if you are using a *’thousand separator’ in your string, things are getting messy …

Or if you are using a comma instead of a dot as the decimal separator you have no luck either …

Depending on the regional settings your users are running your application in, they might have the US notation for decimals (1,234,567.91) or the European one (1.234,567,91).

In this case you can use the following function to simplify the conversion:

func convertLocalizedStringToDouble (decimalAsString: String, thousandSeparator: Bool) -> Double { var formatter = NSNumberFormatter() formatter.usesGroupingSeparator = thousandSeparator formatter.locale = NSLocale.currentLocale() var decimalAsDouble = formatter.numberFromString(decimalAsString)?.doubleValue // The below should never happen! Only happens, if string equals "1,00034.00", so wrong placement of thousand separator if decimalAsDouble == nil { decimalAsDouble = 0} // returning an "Err-Code of 0" if let decimalAsDoubleUnwrapped = formatter.numberFromString(decimalAsString) { decimalAsDouble = decimalAsDoubleUnwrapped.doubleValue } return decimalAsDouble! }

You are calling this function as follows:

<code class="language-swift">var myString: String = "1,234.00" (in case of US locale)  
// var myString: String = "1.234,00" (in case of EU locale)
var result: Double

result = convertLocalizedStringToDouble(myString, True)  

Please note, that the function will return 0 in case your thousand separator is wrongly placed. For instance something like “1,2345.00” on US locale will result in this error.