如何将货币格式化为货币 – Swift 3

我是Swift编程的新手,我已经在Xcode 8.2中创build了一个简单的小费计算器应用程序,我在下面的IBAction中设置了我的计算。 但是当我真正运行我的应用程序,并input一个金额来计算(如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初始值设定项,如果你想强制货币为$:

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

最好的办法是创build一个NSNumberFormatter 。 (Swift 3中的NumberFormatter )。您可以请求货币,它将设置string以遵循用户的本地化设置,这很有用。

如果你想强制美国格式的美元和美分string,你可以这样格式化:

 let amount: Double = 123.45 let amountString = String(format: "$%.02f", amount) 

除了其他人讨论的NumberFormatterString(format:) ,您可能还想考虑使用DecimalNSDecimalNumber并自己控制四舍五入,从而避免浮点问题。 如果你正在做一个简单的小费计算器,这可能是没有必要的。 但是,如果您在一天结束时做了诸如加总提示之类的事情,那么如果您不使用十进制数字进行数字整理和/或math运算,则可以引入错误。

所以,请继续并configuration您的格式化程序:

 let formatter: NumberFormatter = { let _formatter = NumberFormatter() _formatter.numberStyle = .decimal _formatter.minimumFractionDigits = 2 _formatter.maximumFractionDigits = 2 _formatter.generatesDecimalNumbers = true return _formatter }() 

然后使用十进制数字:

 let string = "2.03" let tipRate = Decimal(sign: .plus, exponent: -3, significand: 125) // 12.5% guard let billAmount = formatter.number(from: string) as? Decimal else { return } let tip = (billAmount * tipRate).rounded(2) guard let output = formatter.string(from: tip as NSDecimalNumber) else { return } print("\(output)") 

哪里

 extension Decimal { /// Round `Decimal` number to certain number of decimal places. /// /// - Parameters: /// - scale: How many decimal places. /// - roundingMode: How should number be rounded. Defaults to `.plain`. /// - Returns: The new rounded number. func rounded(_ scale: Int, roundingMode: RoundingMode = .plain) -> Decimal { var value = self var result: Decimal = 0 NSDecimalRound(&result, &value, scale, roundingMode) return result } } 

很明显,你可以用上述所有的“2位小数”引用来代替所用的货币号码(或者用一个variables来表示小数位数)。

就是这样:

  let currentLocale = Locale.current let currencySymbol = currentLocale.currencySymbol let outputString = "\(currencySymbol)\(String(format: "%.2f", totalBillAmount))" 

第一行:您正在获取当前的语言环境

第二行:您将获得该语言环境的currencySymbol。 ($,£等)

第三行:使用格式初始化程序将您的Double截断为2位小数。