我是Swift编程的新手,我已经在Xcode 8.2中创建了一个简单的小费计算器应用程序,我的计算在下面的IBAction中进行了设置。但是,当我实际运行我的应用并输入要计算的金额(例如23.45)时,它的位数超过了2个小数位。在这种情况下,如何将其格式化为.currency

@IBAction func calculateButtonTapped(_ sender: Any) {

    var tipPercentage: Double {

        if tipAmountSegmentedControl.selectedSegmentIndex == 0 {
            return 0.05
        } else if tipAmountSegmentedControl.selectedSegmentIndex == 1 {
            return 0.10
        } else {
            return 0.2
        }
    }

    let billAmount: Double? = Double(userInputTextField.text!)

    if let billAmount = billAmount {
        let tipAmount = billAmount * tipPercentage
        let totalBillAmount = billAmount + tipAmount

        tipAmountLabel.text = "Tip Amount: $\(tipAmount)"
        totalBillAmountLabel.text = "Total Bill Amount: $\(totalBillAmount)"
    }
}

最佳答案

如果要将货币强制为$,可以使用此字符串初始化程序:

String(format: "Tip Amount: $%.02f", tipAmount)

如果希望它完全取决于设备的语言环境设置,则应使用NumberFormatter。这将考虑到货币的小数位数以及正确放置货币符号。例如。 double值2.4将为es_ES语言环境返回“2,40€”,为jp_JP语言环境返回“¥2”。
let formatter = NumberFormatter()
formatter.locale = Locale.current // Change this to another locale if you want to force a specific locale, otherwise this is redundant as the current locale is the default already
formatter.numberStyle = .currency
if let formattedTipAmount = formatter.string(from: tipAmount as NSNumber) {
    tipAmountLabel.text = "Tip Amount: \(formattedTipAmount)"
}

关于ios - 如何将Double格式化为Currency-Swift 3,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41558832/

10-12 01:05