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?
By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.
All that we have to do is to set its numberStyle to currency and give it the code of the currency that we're using — like this: extension Price: CustomStringConvertible { var description: String { let formatter = NumberFormatter() formatter. numberStyle = . currency formatter.
If you'd like to interpolate a float or a double with a String in Swift, use the %f String format specifier with appropriate number in order to specify floating point precision. Note that Swift automatically rounds the value for you.
In Swift, there are two types of floating-point number, both of which are signed. These are the Float type which represents 32-bit floating point numbers with at least 6 decimal digits of precision and the Double type which represents 64-bit floating point numbers at least 15 decimal digits of precision.
You can just cast your Decimal
to an NSDecimalNumber
first:
let priceString = currencyFormatter.string(from: myTotal as NSDecimalNumber)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With