如何将 Double 格式化为 Currency-Swift 3

我是 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)"
}
}
93447 次浏览

如果要将货币强制为 $,可以使用此字符串初始值设定项:

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

如果希望它完全依赖于设备的区域设置,则应使用 NumberFormatter。这将考虑到货币的小数位数以及货币符号的正确位置。例如,双精度值2.4将为 es _ ES 区域设置返回“2.40 something”,为 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)"
}

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

作为使用 NumberFormatter 的替代方法,如果您想强制使用美元和美分格式的字符串,您可以这样格式化它:

let amount: Double = 123.45


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

方法如下:

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

第一行: 获取当前的地区

第二行: 你得到了那个地区的货币符号($,等等)

第3行: 使用格式初始值设定项将 Double 截断为小数点后2位。

除了其他人讨论的 NumberFormatterString(format:)之外,您可能还需要考虑使用 DecimalNSDecimalNumber并自己控制舍入,从而避免浮点问题。如果你正在做一个简单的小费计算器,这可能是没有必要的。但是如果你在一天结束的时候做一些类似于加总技巧的事情,如果你没有四舍五入或者用十进制数做数学计算,你可能会引入错误。

因此,继续配置您的格式化程序:

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位”引用。

您可以像这样进行转换: 这个 func 转换可以随时为您保留最大的 FractionDigits

static func df2so(_ price: Double) -> String{
let numberFormatter = NumberFormatter()
numberFormatter.groupingSeparator = ","
numberFormatter.groupingSize = 3
numberFormatter.usesGroupingSeparator = true
numberFormatter.decimalSeparator = "."
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 2
return numberFormatter.string(from: price as NSNumber)!
}

我在类 Model 中创建它 然后当你调用时,你可以接受另一个类,像这样

 print("InitData: result convert string " + Model.df2so(1008977.72))
//InitData: result convert string "1,008,977.72"

如何在 Swift 4中做到:

let myDouble = 9999.99
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
// localize to your grouping and decimal separator
currencyFormatter.locale = Locale.current


// We'll force unwrap with the !, if you've got defined data you may need more error checking


let priceString = currencyFormatter.string(from: NSNumber(value: myDouble))!
print(priceString) // Displays $9,999.99 in the US locale

你可以为字符串或者整数创建一个扩展,我会展示一个有字符串的例子

extension String{
func toCurrencyFormat() -> String {
if let intValue = Int(self){
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "ig_NG")/* Using Nigeria's Naira here or you can use Locale.current to get current locale, please change to your locale, link below to get all locale identifier.*/
numberFormatter.numberStyle = NumberFormatter.Style.currency
return numberFormatter.string(from: NSNumber(value: intValue)) ?? ""
}
return ""
}
}

链接以获取所有区域设置标识符

extension Float {
var localeCurrency: String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = .current
return formatter.string(from: self as NSNumber)!
}
}
amount = 200.02
print("Amount Saved Value ",String(format:"%.2f", amountSaving. localeCurrency))

对我来说,它的回报0.00! 在我看来扩展完美的时候访问它返回0.00! 为什么?

 extension String{
func convertDoubleToCurrency() -> String{
let amount1 = Double(self)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency
numberFormatter.locale = Locale(identifier: "en_US")
return numberFormatter.string(from: NSNumber(value: amount1!))!
}
}

这里有一个简单的方法。

extension String {
func toCurrency(Amount: NSNumber) -> String {
var currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale.current


return currencyFormatter.string(from: Amount)!
}
}

用法如下

let amountToCurrency = NSNumber(99.99)
String().toCurrency(Amount: amountToCurrency)

至于 Swift 5.5,你可以在 .formatted的帮助下完成:

import Foundation


let amount = 12345678.9
print(amount.formatted(.currency(code: "USD")))
// prints: $12,345,678.90

这应该支持最常用的货币代码,如“欧元”、“英镑”或“人民币”。

类似地,您可以将 locale 附加到 .currency:

print(amount.formatted(
.currency(code:"EUR").locale(Locale(identifier: "fr-FR"))
))
// prints: 12 345 678,90 €

在2022年,我使用 Swift 5.5创建了一些扩展,可以使用设备的区域设置或者作为参数传递的区域设置将 Float 或 Double 转换为货币。你可以在这里查看 https://github.com/ahenqs/SwiftExtensions/blob/main/Currency.playground/Contents.swift

import UIKit


extension NSNumber {
    

/// Converts an NSNumber into a formatted currency string, device's current Locale.
var currency: String {
return self.currency(for: Locale.current)
}
    

/// Converts an NSNumber into a formatted currency string, using Locale as a parameter.
func currency(for locale: Locale) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.usesGroupingSeparator = locale.groupingSeparator != nil
numberFormatter.numberStyle = .currency
numberFormatter.locale = locale
        

return numberFormatter.string(from: self)!
}
}


extension Double {
    

/// Converts a Double into a formatted currency string, device's current Locale.
var currency: String {
return NSNumber(value: self).currency(for: Locale.current)
}
    

/// Converts a Double into a formatted currency string, using Locale as a parameter.
func currency(for locale: Locale) -> String {
return NSNumber(value: self).currency(for: locale)
}
}


extension Float {
    

/// Converts a Float into a formatted currency string, device's current Locale.
var currency: String {
return NSNumber(value: self).currency(for: Locale.current)
}
    

/// Converts a Float into a formatted currency string, using Locale as a parameter.
func currency(for locale: Locale) -> String {
return NSNumber(value: self).currency(for: locale)
}
}


let amount = 3927.75 // Can be either Double or Float, since we have both extensions.
let usLocale = Locale(identifier: "en-US") // US
let brLocale = Locale(identifier: "pt-BR") // Brazil
let frLocale = Locale(identifier: "fr-FR") // France
print("\(Locale.current.identifier) -> " + amount.currency) // default current device's Locale.
print("\(usLocale.identifier) -> " + amount.currency(for: usLocale))
print("\(brLocale.identifier) -> " + amount.currency(for: brLocale))
print("\(frLocale.identifier) -> " + amount.currency(for: frLocale))


// will print something like this:
// en_US -> $3,927.75
// en-US -> $3,927.75
// pt-BR -> R$ 3.927,75
// fr-FR -> 3 927,75 €

我希望它有帮助,快乐编码!