icekomo
icekomo

Reputation: 9466

How to use currencyFormatter with a decimal

I'm trying to take a decimal I'm storing in CoreData and run it through the currency formatter in Swift 3. Here is what I'm trying to use:

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

Where totalAmount is the decimal I'm using for CoreData.

But . I get this error when trying to convert my decimal to a NSNumber()

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

Upvotes: 0

Views: 172

Answers (2)

Sulthan
Sulthan

Reputation: 130072

stringFromNumber got renamed to string(from:), e.g.

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

but you don't have to convert to NSNumber

var priceString = currencyFormatter.string(for: totalAmount)

Upvotes: 1

GIJOW
GIJOW

Reputation: 2343

You can have something like:

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

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

    return formatter
  }()
}

Usage:

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

Upvotes: 0

Related Questions