I receive the following JSON response:
{
"id": 1,
"value": 519.6365
}
But when I convert the value
to Double
, I get: 519.63649999999996
How to keep the original value? (without rounding it)
I receive the following JSON response:
{
"id": 1,
"value": 519.6365
}
But when I convert the value
to Double
, I get: 519.63649999999996
How to keep the original value? (without rounding it)
In such case using Foundation's NSNumber would be better solution. Converts the json value to NSNumber and it can always be downcast to Double Value
In Swift 4 -
let json = [
"id": 1,
"value": 519.6365
]
let value = (json["value"]! as NSNumber).doubleValue
print(value) // Outputs - 519.6365
In cases where server sends the value as string, it would need to be first casted as String then to double value as -
value = (json["value"]! as NSString).doubleValue
Double is like long Float,
Double represents a 64-bit floating-point number.
Float represents a 32-bit floating-point number.
So when you cast to Double, 32 bits is added to the variable, causing the change you see.
To keep the number as it is, you need to cast the variable to Float meaning the smaller floating point number.
var value:Float = 519.6365
var valueDouble = Double(value) // 519.636474609375
Float(valueDouble) // 519.6365