Swift - How to convert String to Double

2019-01-01 14:52发布

I'm trying to write a BMI program in swift language. And I got this problem: how to convert a String to a Double?

In Objective-C, I can do like this:

double myDouble = [myString doubleValue];

But how can I achieve this in Swift language?

28条回答
看风景的人
2楼-- · 2019-01-01 15:25

This is building upon the answer by @Ryu

His solution is great as long as you're in a country where dots are used as separators. By default NSNumberFormatter uses the devices locale. Therefore this will fail in all countries where a comma is used as the default separator (including France as @PeterK. mentioned) if the number uses dots as separators (which is normally the case). To set the locale of this NSNumberFormatter to be US and thus use dots as separators replace the line

return NSNumberFormatter().numberFromString(self)?.doubleValue

with

let numberFormatter = NSNumberFormatter()
numberFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return numberFormatter.numberFromString(self)?.doubleValue

Therefore the full code becomes

extension String {
    func toDouble() -> Double? {
        let numberFormatter = NSNumberFormatter()
        numberFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
        return numberFormatter.numberFromString(self)?.doubleValue
    }
}

To use this, just call "Your text goes here".toDouble()

This will return an optional Double?

As @Ryu mentioned you can either force unwrap:

println("The value is \(myDouble!)") // prints: The value is 4.2

or use an if let statement:

if let myDouble = myDouble {
    println("The value is \(myDouble)") // prints: The value is 4.2
}
查看更多
萌妹纸的霸气范
3楼-- · 2019-01-01 15:25

Swift :- 4

There are possibly two ways to do this:

  1. String -> Int -> Double:

    let strNumber = "314"
    let intFromString = Int(strNumber)
    let dobleFromInt = Double(intFromString!)
    print(dobleFromInt)
    
  2. String -> NSString -> Double

    let strNumber = "314"
    let NSstringFromString = NSString(string: strNumber as! NSString)
    let doubleFromNSString = NSstringFromString.doubleValue
    print(doubleFromNSString)
    

Use it anyway you like according to you need of the code.

查看更多
公子世无双
4楼-- · 2019-01-01 15:26

Swift 4.0

try this

 let str:String = "111.11"
 let tempString = (str as NSString).doubleValue
 print("String:-",tempString)
查看更多
查无此人
5楼-- · 2019-01-01 15:29

On SWIFT 3, you can use:

if let myDouble = NumberFormatter().number(from: yourString)?.doubleValue {
   print("My double: \(myDouble)")
}

Note: - If a string contains any characters other than numerical digits or locale-appropriate group or decimal separators, parsing will fail. - Any leading or trailing space separator characters in a string are ignored. For example, the strings “ 5”, “5 ”, and “5” all produce the number 5.

Taken from the documentation: https://developer.apple.com/reference/foundation/numberformatter/1408845-number

查看更多
还给你的自由
6楼-- · 2019-01-01 15:30

As of Swift 1.1, you can directly pass String to const char * parameter.

import Foundation

let str = "123.4567"
let num = atof(str) // -> 123.4567

atof("123.4567fubar") // -> 123.4567

If you don't like deprecated atof:

strtod("765.4321", nil) // -> 765.4321

One caveat: the behavior of conversion is different from NSString.doubleValue.

atof and strtod accept 0x prefixed hex string:

atof("0xffp-2") // -> 63.75
atof("12.3456e+2") // -> 1,234.56
atof("nan") // -> (not a number)
atof("inf") // -> (+infinity)

If you prefer .doubleValue behavior, we can still use CFString bridging:

let str = "0xff"
atof(str)                      // -> 255.0
strtod(str, nil)               // -> 255.0
CFStringGetDoubleValue(str)    // -> 0.0
(str as NSString).doubleValue  // -> 0.0
查看更多
人气声优
7楼-- · 2019-01-01 15:30

SWIFT 4

extension String {
    func toDouble() -> Double? {
        let numberFormatter = NumberFormatter()
        numberFormatter.locale = Locale(identifier: "en_US_POSIX")
        return numberFormatter.number(from: self)?.doubleValue
    }
}
查看更多
登录 后发表回答