2

How do I convert a string to double in Swift? I've tried string.doubleValue or string.bridgeToObjectiveC().doubleValue and none of it works. Any ideas?

Jason Ze
  • 63
  • 1
  • 2
  • 6

5 Answers5

6

You can create a read-only computed property string extension to help you convert your strings to double:

You can use NSNumberFormatter

extension String {
    struct Number {
        static let formatter = NSNumberFormatter()
    }
    var doubleValue: Double {
        return Number.formatter.numberFromString(self)?.doubleValue ?? 0
    }
}

or you can cast it to NSString and extract its doubleValue property:

extension String {
    var ns: NSString {
        return self
    }
    var doubleValue: Double {
        return ns.doubleValue
    }
}

"2.35".doubleValue + 3.3 // 5.65
Leo Dabus
  • 198,248
  • 51
  • 423
  • 494
  • this works fine in the simulator, whysoever not on my iPhone6 (ios8.4). This Solution works fine: [http://stackoverflow.com/questions/24031621/swift-how-to-convert-string-to-double](http://stackoverflow.com/questions/24031621/swift-how-to-convert-string-to-double) – alexdd55 Aug 02 '15 at 16:04
4

According to Stanford CS193p course Winter 2015, the correct way to get a double from a String in Swift is to use NSNumberFormatter instead of NSString:

let decimalAsString = "123.45"
let decimalAsDouble = NSNumberFormatter().numberFromString(decimalAsString)!.doubleValue

If you want to be safe (regarding the optional unwrapping and the decimal separator), you'd use:

 let decimalAsString = "123.45"
 var formatter = NSNumberFormatter()
 formatter.locale = NSLocale(localeIdentifier: "en_US")
 if let decimalAsDoubleUnwrapped = formatter.numberFromString(decimalAsString) {
   decimalAsDouble = decimalAsDoubleUnwrapped.doubleValue
}

Safe unwrapping is particularly useful if you parse a XML or JSON file and you need to make sure you have a String that can be converted into a Double (the program will crash if you force-unwrap an optional that is actually nil).

/!\ EDIT: be careful, NSNumberFormatter works differently than NSString. NSString allowed you to do things like : (dictionary[key] as NSString).doubleValue, provided that dictionary[key] used the '.' as decimal separator (like in "123.45"). But NSNumberFormatter(), by default, initializes an instance of NSNumberFormatter with your current system Locale! Therefore, NSNumberFormatter().numberFromString(decimalAsString)!.doubleValue would work with 123.45 on a US device, but not on a French one for example! If you are parsing a JSON file for example, and you know that values are stored using '.' as the decimal separator, you need to set the locale of your NSNumberFormatter instance accordingly:

var formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US")

then:

let decimalAsString = "123.45"
if let decimalAsDoubleUnwrapped = NSNumberFormatter().numberFromString(decimalAsString) {
   decimalAsDouble = decimalAsDoubleUnwrapped.doubleValue
}

In that case, decimalAsDouble will correctly return 123.45 as a doubleValue.

But it would return nil if decimalAsString = "123,45". Or if the NSLocale was set as "fr_FR". On the other hand, a NSNumberFormatter using a NSLocale with fr_FR would work perfectly with "123,45", but return nil with "123.45".

I thought that was worth reminding. I updated my answer accordingly.

EDIT : also, NSNumberFormatter wouldn't know what do with things like "+2.45%" or "0.1146"(you would have to define the properties of your NSNumberFormatter instance very precisely). NSString natively does.

Frédéric Adda
  • 5,240
  • 4
  • 50
  • 67
2

you can always just cast from String to NSString like this

let str = "5"
let dbl = (str as NSString).doubleValue
Alpine
  • 1,329
  • 12
  • 13
  • 1
    NSString's floatValue and doubleValue methods only work when the numbers use the US style dot separator. [This property uses formatting information stored in the non-localized value; use an NSScanner object for localized scanning of numeric values from a string.](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/#//apple_ref/occ/instp/NSString/doubleValue) – iluvatar_GR Dec 12 '14 at 13:00
2

Try this :

var a:Double=NSString(string: "232.3").doubleValue
Dhruv Ramani
  • 2,536
  • 2
  • 19
  • 29
-1

Try this:

let str = "5"
let double = Double(str.toInt()!)

another way is:

let mySwiftString = "5"
var string = NSString(string: mySwiftString)
string.doubleValue

this latter one posted here:

Swift - How to convert String to Double

Community
  • 1
  • 1
Steve Rosenberg
  • 18,504
  • 7
  • 42
  • 50