如何使用带小数的 currencyFormatter

How to use currencyFormatter with a decimal

我正在尝试获取我存储在 CoreData 中的小数点,并通过 Swift 中的货币格式化程序 运行 获取它 3. 这是我正在尝试使用的内容:

var currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = NumberFormatter.Style.currency
// localize to your grouping and decimal separator
currencyFormatter.locale = NSLocale.current
var priceString = currencyFormatter.stringFromNumber(NSNumber(totalAmount))

其中 totalAmount 是我用于 CoreData 的小数。

但是。尝试将小数转换为 NSNumber()

时出现此错误

Argument labels '(_:)' do not match any available overloads

你可以有这样的东西:

class YourClass: UIViewController {
  static let priceFormatter: NumberFormatter = {
    let formatter = NumberFormatter()

    formatter.formatterBehavior = .behavior10_4
    formatter.numberStyle = .currency

    return formatter
  }()
}

用法:

yourLabel.text = YourClass.priceFormatter.string(from: totalAmount)

stringFromNumber 已重命名为 string(from:),例如

var priceString = currencyFormatter.string(from: NSNumber(totalAmount))

但您不必转换为 NSNumber

var priceString = currencyFormatter.string(for: totalAmount)