出于某种原因,我无法将Price字符串转换为双精度。当我这样做时,它总是返回nil。
func calculateAirfare(checkedBags: Int, distance: Int, travelers: Int) {
let bagsPrices = Double(checkedBags * 25)
let mileCosts = Double(distance) * 0.10
let price = (bagsPrices + mileCosts) * Double(travelers)
/// Format price
let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
let priceString = currencyFormatter.string(from: NSNumber(value: price))
print(priceString) -> "Optional("$750.00")"
if let double = Double(priceString) {
print(double) -> nil
}
}
价格已经是订单价格的两倍
let price = (bagsPrices + mileCosts) * Double(travelers)
因此无需将其转换为两倍。下面的代码将返回带有$符号的字符串
currencyFormatter.string(from: NSNumber(value: price))
要从该字符串中获取双精度字,则需要删除$符号
您可以使用removeFirst()完成的操作>
priceString?.removeFirst()
之后,字符串可以转换为Double。完整的代码是:
func calculateAirfare(checkedBags: Int, distance: Int, travelers: Int) {
let bagsPrices = Double(checkedBags * 25)
let mileCosts = Double(distance) * 0.10
let price = (bagsPrices + mileCosts) * Double(travelers)
/// Format price
let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
var priceString = currencyFormatter.string(for: price)
priceString?.removeFirst()
print(priceString!)
if let double = Double(priceString!) {
print(double)
}
}
您可以使用相同的格式化程序返回到这样的数字: