gpt4 book ai didi

ios - 如何将 Double 格式化为货币 - Swift 3

转载 作者:bug小助手 更新时间:2023-10-28 10:43:41 25 4
gpt4 key购买 nike

我是 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。这将考虑货币的小数位数以及正确定位货币符号。例如。对于 es_ES 语言环境, double 值 2.4 将返回“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 格式化为货币 - Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41558832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com