Oxthor
Oxthor

Reputation: 522

NumberFormatter grouping not working as expected

Working on currency formatting, I've found an issue when trying to format Chilean pesos.

Following this code:

let priceFormatter = NumberFormatter()
priceFormatter.locale = Locale(identifier: "es_CL")
priceFormatter.numberStyle = .currency
priceFormatter.currencyCode = "CLP"

priceFormatter.string(from: 9990) // A
priceFormatter.string(from: 99900) // B

Executing this I get $9990 for A and $99.990 for B.
What I want to achieve is $9.990 for A

Looks like the formatter is not adding the thousand grouping separator on the first case, which I am not sure why. I have tried adding setting the groupingSize to 3 without success.

(This only happens with 4 digits)

Upvotes: 5

Views: 2243

Answers (2)

Mateusz
Mateusz

Reputation: 233

I had the same issue and found explanation here: iOS13: NumberFormatter missing groupingSeparator when try to format 4 digits numbers with es_ES locale

I ended up setting us_US locale:

let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "us_US")
formatter.groupingSeparator = " "
formatter.usesGroupingSeparator = true
formatter.groupingSize = 3

Upvotes: 5

Gabriel Candia
Gabriel Candia

Reputation: 282

I was trying to achieve the same thing, what I ended up doing was this:

let price: Double = 1000
let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .decimal
currencyFormatter.groupingSeparator = "."
currencyFormatter.maximumFractionDigits = 0
let balanceText = currencyFormatter.string(from: NSNumber(value: price))!

return "$" + balanceText

Upvotes: 1

Related Questions