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

Please check it on playground!

let sString = "236.86"

var dNumber = NSNumberFormatter().numberFromString(sString)
var nDouble = dNumber!
var eNumber = Double(nDouble) * 3.7

By the way in my Xcode

.toDouble() - doesn't exist

.doubleValue create value 0.0 from not numerical strings...

查看更多
旧人旧事旧时光
3楼-- · 2019-01-01 15:51

As already pointed out, the best way to achieve this is with direct casting:

(myString as NSString).doubleValue

Building from that, you can make a slick native Swift String extension:

extension String {
    var doubleValue: Double {
        return (self as NSString).doubleValue
    }
}

This allows you to directly use:

myString.doubleValue

Which will perform the casting for you. If Apple does add a doubleValue to the native String you just need to remove the extension and the rest of your code will automatically compile fine!

查看更多
余生请多指教
4楼-- · 2019-01-01 15:51

Or you could do:

var myDouble = Double((mySwiftString.text as NSString).doubleValue)
查看更多
孤独寂梦人
5楼-- · 2019-01-01 15:52

You can use StringEx. It extends String with string-to-number conversions including toDouble().

extension String {
    func toDouble() -> Double?
}

It verifies the string and fails if it can't be converted to double.

Example:

import StringEx

let str = "123.45678"
if let num = str.toDouble() {
    println("Number: \(num)")
} else {
    println("Invalid string")
}
查看更多
登录 后发表回答