0

我有一本字典,其中 Bill Price 作为 Optional Any 我的问题是我想使用以下函数将其转换为货币:

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

我使用以下数据: dicType.value(forKey: "BON_PRIX") -> 可选 - 一些:103.28

我试过了:

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

但我遇到了致命错误,

在展开可选值时意外发现 nil

我尝试了几件事,但没有找到正确的方法。因此,关键是将来自外部服务器的数据转换为欧元,并带有 2 位小数。

在此先感谢您的帮助!

4

2 回答 2

0

你真的不需要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 }) ?? ""
于 2019-09-11T15:16:42.383 回答
-1
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 €")
于 2019-09-11T15:11:52.957 回答