转换货币格式器到双快速

时间:2020-01-15 23:36:59

标签: ios swift

由于某种原因,我无法将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

        }
    }

2 个答案:

答案 0 :(得分:0)

您可以使用相同的格式化程序返回到这样的数字:

let number = currencyFormatter.number(from: priceString)

并获得doubleValue,例如:

let numberDouble = number.doubleValue

答案 1 :(得分:-1)

价格已经是行价的两倍

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)
    }
}