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 Decimal
s 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 Decimal
seem 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 Decimal
s in Swift?
string(for: myTotal)
instead ofstring(from:
– AhmednagarDecimal
overFloat
orDouble
unless you need high precision, which is unlikely for currency. – Bioplasmstring(for: myTotal)
did the trick. Thanks. – PoorhouseDecimal
? – PoorhouseFloat
s. – Bioplasm