【问题标题】:How to use currencyFormatter with a decimal如何使用带小数的currencyFormatter
【发布时间】:2026-01-16 12:35:02
【问题描述】:

我正在尝试获取存储在 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

【问题讨论】:

  • 使用string(from:)string(for:)

标签: ios xcode core-data swift3 currency-formatting


【解决方案1】:

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

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

但您不必转换为NSNumber

var priceString = currencyFormatter.string(for: totalAmount)

【讨论】:

    【解决方案2】:

    你可以有类似的东西:

    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)
    

    【讨论】:

      最近更新 更多