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

Extension with optional locale

Swift 2.2

extension String {
    func toDouble(locale: NSLocale? = nil) -> Double? {
        let formatter = NSNumberFormatter()
        if let locale = locale {
            formatter.locale = locale
        }
        return formatter.numberFromString(self)?.doubleValue
    }
}

Swift 3.1

extension String {
    func toDouble(_ locale: Locale) -> Double {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.locale = locale
        formatter.usesGroupingSeparator = true
        if let result = formatter.number(from: self)?.doubleValue {
            return result
        } else {
            return 0
        }
    }
}
查看更多
余生无你
3楼-- · 2019-01-01 15:40

my problem was comma so i solve it this way:

extension String {
    var doubleValue: Double {
        return Double((self.replacingOccurrences(of: ",", with: ".") as NSString).doubleValue)
    }
}
查看更多
初与友歌
4楼-- · 2019-01-01 15:40

we can use CDouble value which will be obtained by myString.doubleValue

查看更多
看淡一切
5楼-- · 2019-01-01 15:41

In Swift 2.0 the best way is to avoid thinking like an Objective-C developer. So you should not "convert a String to a Double" but you should "initialize a Double from a String". Apple doc over here: https://developer.apple.com/library/ios//documentation/Swift/Reference/Swift_Double_Structure/index.html#//apple_ref/swift/structctr/Double/s:FSdcFMSdFSSGSqSd_

It's an optional init so you can use the nil coalescing operator (??) to set a default value. Example:

let myDouble = Double("1.1") ?? 0.0
查看更多
公子世无双
6楼-- · 2019-01-01 15:41

Swift 4

extension String {
    func toDouble() -> Double {
        let nsString = self as NSString
        return nsString.doubleValue
    }
}
查看更多
无色无味的生活
7楼-- · 2019-01-01 15:42

Another option here is converting this to an NSString and using that:

let string = NSString(string: mySwiftString)
string.doubleValue
查看更多
登录 后发表回答