Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting currency values from JSON to NSDecimalNumber

I get the following JSON response from an API.

{
  "status": "success",
  "data": [
    {
      "actual_price": 30,
      "offered_deal_price": 16,
      "pending_balance": 12.8
    }
  ]
}

All those values are prices. Which means they can be round values or floating values.

I read that you should use NSDecimalNumber type for currency values. I'm having trouble converting these JSON values.

Doing this,

json["pending_balance"] as! NSDecimalNumber

failed with the following error.

Could not cast value of type '__NSCFNumber' (0x10423ccf0) to 'NSDecimalNumber' (0x1046cf1f0)

Trying to cast it to NSDecimal resulted in this

Could not cast value of type '__NSCFNumber' (0x7f9102f79f68) to 'C.NSDecimal' (0x10f23d6e0).

I can however, cast it to Swift types like Float or Double without an issue.

Anyone got an idea what's the problem with NSDecimalNumber? Or is it safe to go ahead with Float or Double? If so which one is the best for currency values?

Thank you.

like image 536
Isuru Avatar asked Feb 09 '23 15:02

Isuru


1 Answers

The error is an indication that you are trying to cast to the wrong type. The value is deserialized from JSON into a NSNumber, which is seamlessly bridged into a Double native swift type.

Rather than casting, you should try with a conversion:

NSDecimalNumber(decimal: (json["pending_balance"] as! NSNumber).decimalValue)

or

NSDecimalNumber(double: json["pending_balance"] as! Double)

but probably there are other ways to do the conversion.

like image 167
Antonio Avatar answered Feb 12 '23 07:02

Antonio