我试图在Swift中将String转换为Double值。经过大量的研究后,我相信这将是将我的字符串转换为Double的最佳方法。但现在我收到一个错误,我不知道如何修复。
var purchaseAmount: Double = 200
var cashTendered: Double = 425.45
var changeRequired: Double = 0
var currencyValues = ["100", "50", "20", "10", "5", "2", "1", "0.50", "0.20", "0.10", "0.05"]
import Cocoa
if cashTendered < purchaseAmount {
println("Not enough cash tendered")
} else {
changeRequired = cashTendered - purchaseAmount
for currency in currencyValues {
var doubleCurrency = (currency as NSString).doubleValue
var amountOfCurrency = changeRequired / doubleCurrency
amountOfCurrency = floor(amountOfCurrency)
changeRequired = changeRequired - (amountOfCurrency * currency)
changeRequired = round(changeRequired * 100)/100
println("$\(currency) X \(Int(amountOfCurrency))")
}
}
这是错误:
我该怎么做才能解决这个问题?
答案 0 :(得分:2)
首先初始化String
数组,如下所示:
let currencyValues : [String] = ["100", "50", "20", "10", "5", "2", "1", "0.50", "0.20", "0.10", "0.05"]
然而,由于Swift具有重要功能Type Interface,因此不需要类型声明。但是大多数练习在使用数组时定义类型是很好的。
关于将字符串转换为double,您可以使用以下代码:
for currency : String in currencyValues {
let doubleCurrency = NSNumberFormatter().numberFromString(currency)!.doubleValue
print(doubleCurrency)
}
答案 1 :(得分:0)
发布代码比图像更容易查看,但如果所有其他方法都失败则有NSNumberFormatter。 NSNumberFormatter的其他优点是允许您转换两个方向并获得货币等方面的良好输出。