问题描述
我正在尝试用 swift 语言编写一个 BMI 程序.我遇到了这个问题:如何将 String 转换为 Double?
I'm trying to write a BMI program in swift language.And I got this problem: how to convert a String to a Double?
在 Objective-C 中,我可以这样做:
In Objective-C, I can do like this:
double myDouble = [myString doubleValue];
但是我如何用 Swift 语言实现这一点?
But how can I achieve this in Swift language?
推荐答案
Swift 4.2+ String to Double
您应该使用新的类型初始值设定项在字符串和数字类型(Double、Float、Int)之间进行转换.它将返回一个 Optional 类型(Double?),如果 String 不是数字,它将具有正确的值或 nil.
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.
注意:不推荐使用 NSString doubleValue 属性,因为如果值无法转换(即:错误的用户输入),它会返回 0.
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
使用 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!)")
}
您可以使用 NumberFormatter
类转换格式化的数字和货币.
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")
货币格式
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")
阅读更多关于我的关于将 String 转换为 Double 类型(和货币)的博客文章.
这篇关于Swift - 如何将字符串转换为双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!