fs_tigre
fs_tigre

Reputation: 10748

How to format Decimal in Swift 3

I'm trying to use the Swift Decimal Structure for currency operations but I cannot format it.

How can I format var myDecimal:Decimal = 9999.99 to display $9,999.99?

Without using Decimals I can do it as follow...

let myTotal:NSNumber = 9999.99

let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true

currencyFormatter.numberStyle = .currency
currencyFormatter.locale = NSLocale.current
let priceString = currencyFormatter.string(from: myTotal)

myLabel.text = priceString

This works fine but I have been reading and Decimalseem to be the right type for currency.

I tried...

let myTotal:Decimal = 9999.99

let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true

currencyFormatter.numberStyle = .currency
// localize to your grouping and decimal separator
currencyFormatter.locale = NSLocale.current
let priceString = currencyFormatter.string(from: NSNumber(myTotal))

myLabel.text = priceString

... but I get error

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

What is the right way to format Decimals in Swift?

Upvotes: 7

Views: 5462

Answers (1)

Charles Srstka
Charles Srstka

Reputation: 17060

You can just cast your Decimal to an NSDecimalNumber first:

let priceString = currencyFormatter.string(from: myTotal as NSDecimalNumber)

Upvotes: 9

Related Questions