sandra dev
sandra dev

Reputation: 41

format currency - remove decimals

I need to convert from cents to euros

{
ref: "1dsdsd",
title: "XXXXXX",

price: 92820
},
{
ref: "2ddsds",
title: "XXXXXX",

price: 12830
},
{
ref: "3dsds",
title: "XXXXXXX",
price: 885
} 
]

if the value is 885 cents, we should read 8.85euros, but the values returned by the webservice are not consistent : 2, 3 , 5 digits

my solution does not allow to return a value in euros by removing the extra decimals

extension Int {
    func format() -> String {
        let double = Double(self) / 100
        return String(format: "€ %.02f", double)
    }

}

enter image description here

Upvotes: 0

Views: 1300

Answers (1)

CRD
CRD

Reputation: 53000

Don't try todo this with your own code as there are too many variables to take account of. Instead use a NumberFormatter, set its numberStyle to the appropriate currency style you need.

If your code is not running in a locale where the currency is euros you can set the formatter's locale property to one where it is – don't to to change the currency symbol by setting the currencyCode or related properties, a locale carries more information about the layout.

Your values are in integer cents, a good choice for currency values, unfortunately NumberFormatter expects the unit to be euros (or pound etc.). You can address this in two ways (a) pre-divide the number by 100 before passing it to the formatter or (b) set the formatter's multiplier property to 0.01 (Note: in this latter case you must still pass the number to be formatted as floating point (e.g. Double) or the cents will get truncated, this is a feature/bug of NumberFormatter)

Upvotes: 2

Related Questions