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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With