Issue while trying to convert dic value to currency value

70 Views Asked by At

I have a dictionary with Bill Price as Optional Any My issue is that I want to convert it in Currency with the function below:

let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale.current
let priceString = currencyFormatter.string(from: ToConvert2)
print(priceString) // Displays $9,999.99 in the US locale

Im using the following data: dicType.value(forKey: "BON_PRIX") --> Optional - some : 103.28

I tried:

let ToConvert = (String(describing: dicType.value(forKey: "BON_PRIX") as! String))
let ToConvert2 = NSNumber(value: Int(ToConvert)!)

but I'm getting Fatal error,

Unexpectedly found nil while unwrapping an Optional value

I tried few things but didn't find the right way. So the point is to convert data from an external server into EUR with roundup with 2 decimals.

Thanks in advance for your help!

2

There are 2 best solutions below

9
Amyth On
func getEuro(strVal: String) -> String? {

   let doubleStr = Double(strVal)

   let price = doubleStr as? NSNumber

   print(price)

   let formatter = NumberFormatter()

   formatter.numberStyle = .currency

   // Changing locale to "es_ES" for Spanish Locale to get Euro currency format.

   formatter.locale = Locale(identifier: "es_ES")

   if let price = price {
      let euroPrice = formatter.string(from: price)
      print(euroPrice!) //"103,28 €"

      return euroPrice
   }

   return nil
}

print(getEuro(strVal: "103.28")) //Optional("103,28 €")
4
Sulthan On

You don't really need NSNumber:

let value = dicType["BON_PRIX"] as? String
// safely convert String to Double
let roundedDoubleValue = value.flatMap { Double($0) }
// use .string(for:) instead of .string(from:)
let priceString = currencyFormatter.string(for: roundedDoubleValue }) ?? ""