Swift: Converting String to Double


Converting 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:

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.

About Jeannot Muller

"The future is now! The cost of being wrong about IT is greater than it has ever been... you really need to get it right the first time these days!" I worked in different executive management positions with Deutsche Post DHL. Before my engagement with DPDHL I was employed by CIBER, where I was part of the management team and responsible for project and development management in various IT projects for large to very large international customers. Before CIBER I ran my own publishing company in the health sector. Currently I'm running my own consulting company Dr. Jeannot Muller Consulting & Publishing, as a Freelancer. I'm the technical CEO and founder of https://teccompanion.com, which is my main business.

Kommentar verfassen