Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 731
fs_tigre Avatar asked Sep 08 '17 00:09

fs_tigre


People also ask

How do you round to 2 decimal places in Swift?

By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.

How do I change the number format 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.

How do I set precision in Swift?

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.

What is decimal in Swift?

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.


1 Answers

You can just cast your Decimal to an NSDecimalNumber first:

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

like image 99
Charles Srstka Avatar answered Sep 29 '22 22:09

Charles Srstka