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

Swift 4.2+ String to Double

You should use the new type initializers to convert between String and numeric types (Double, Float, Int). It'll return an Optional type (Double?) which will have the correct value or nil if the String was not a number.

Note: The NSString doubleValue property is not recommended because it returns 0 if the value cannot be converted (i.e.: bad user input).

let lessPrecisePI = Float("3.14")

let morePrecisePI = Double("3.1415926536")
let invalidNumber = Float("alphabet") // nil, not a valid number

Unwrap the values to use them using if/let

if let cost = Double(textField.text!) {
    print("The user entered a value price of \(cost)")
} else {
    print("Not a valid number: \(textField.text!)")
}

You can convert formatted numbers and currency using the NumberFormatter class.

let formatter = NumberFormatter()
formatter.locale = Locale.current // USA: Locale(identifier: "en_US")
formatter.numberStyle = .decimal
let number = formatter.number(from: "9,999.99")

Currency formats

let usLocale = Locale(identifier: "en_US")
let frenchLocale = Locale(identifier: "fr_FR")
let germanLocale = Locale(identifier: "de_DE")
let englishUKLocale = Locale(identifier: "en_GB") // United Kingdom
formatter.numberStyle = .currency

formatter.locale = usLocale
let usCurrency = formatter.number(from: "$9,999.99")

formatter.locale = frenchLocale
let frenchCurrency = formatter.number(from: "9999,99€")
// Note: "9 999,99€" fails with grouping separator
// Note: "9999,99 €" fails with a space before the €

formatter.locale = germanLocale
let germanCurrency = formatter.number(from: "9999,99€")
// Note: "9.999,99€" fails with grouping separator

formatter.locale = englishUKLocale
let englishUKCurrency = formatter.number(from: "£9,999.99")

Read more on my blog post about converting String to Double types (and currency).

查看更多
残风、尘缘若梦
3楼-- · 2019-01-01 15:34

SWIFT 3

To clear, nowadays there is a default method:

public init?(_ text: String) of Double class.

It can be used for all classes.

let c = Double("-1.0") let f = Double("0x1c.6") let i = Double("inf") , etc.

查看更多
浅入江南
4楼-- · 2019-01-01 15:35

I haven't seen the answer I was looking for. I just post in here mine in case it can help anyone. This answer is valid only if you don't need an specific format.

Swift 3

extension String {
    var toDouble: Double {
        return Double(self) ?? 0.0
    }
}
查看更多
墨雨无痕
5楼-- · 2019-01-01 15:37

Use this code in Swift 2.0

let strWithFloat = "78.65" let floatFromString = Double(strWithFloat)

查看更多
不流泪的眼
6楼-- · 2019-01-01 15:38

1.

let strswift = "12"
let double = (strswift as NSString).doubleValue

2.

var strswift= "10.6"
var double : Double = NSString(string: strswift).doubleValue 

May be this help for you.

查看更多
还给你的自由
7楼-- · 2019-01-01 15:38
var stringValue = "55"

var convertToDouble = Double((stringValue as NSString).doubleValue)
查看更多
登录 后发表回答