4

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.

Community
  • 1
  • 1
Isuru
  • 30,617
  • 60
  • 187
  • 303

1 Answers1

8

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.

Antonio
  • 71,651
  • 11
  • 148
  • 165
  • Thanks, Antonio. I went with the first suggestion and it works. – Isuru Jul 08 '15 at 18:53
  • 3
    Note: this will solve the casting issue but not the original problem of inprecise floating point representation. The right solution is to convert the string in Swift to NSDecimalNumber, not in JS. – Mike Lischke Jul 12 '15 at 13:05