Search code examples
iosswiftnumberformatter

Swift iOS -How to set one user's formatter.locale from another user's formatter.locale


userA is in France, they set a price for something to €10 and I get their currency info and I record a copy of their local region to the db using Locale.current.identifier which gives me and I save it to dataModel.localeIdentifier

// when userA uploads
let formatter = NumberFormatter()
formatter.usesGroupingSeparator = true
formatter.numberStyle = .currency
formatter.locale = Locale.current
formatter.numberStyle = NumberFormatter.Style.currency

// save their Locale.current.identifier to the db
dataModel.localeIdentifier = Locale.current.identifier

userB is in GreatBritain, they see what userA has posted and maybe they want to purchase 2 of them for €20 which means I have to remove the euro symbol, do some calculations, then add the euro symbol back later on. Instead of manually appending it back on I just want to use the dataModel.localeIdentifier from userA and set it to the formatter that userB using. That way the euro symbol would appear on the new amount of 20

Instead of using userB's Locale.current.identifier which would show pounds I want it to show the Euro symbol. I tried this but it's not working

// userB
let amount = updatedAmount(amount: 20) // strips away the € sign and just uses the Double
let formatter = NumberFormatter()        
formatter.usesGroupingSeparator = true
formatter.numberStyle = .currency

// identifierFromUserA is €
let identifierFromUserA = dataModel.localeIdentifier // this isn't nil because I'm force unwrapping it below
let localeFromUserA = Locale(identifier: identifierFromUserA!)

 // *** after setting userB's formatter.locale to the one from localeFromUserA I'm still getting the local currency instead of the € ***
formatter.locale = localeFromUserA

formatter.numberStyle = NumberFormatter.Style.currency

// this should now show €20
let newAmount = formatter.string(from: NSNumber(value: amount))

The problem is after setting userB's formatter.locale to localeFromUserA I'm still getting userB's local currency instead of the €


Solution

  • It was a coding error, I found the mistake, when setting the userA's dataModel.localeIdentifier = Locale.current.identifier I had another function that later changed it to dataModel.localeIdentifier = Locale.current.currencySymbol that's why I was getting the euro symbol instead of en_FR