I'm using AlamoFire to call my web service:
ApiManager.manager.request(.GET, webServiceCallUrl, parameters: ["id": 123])
.validate()
.responseJSON { response in
switch response.result {
case .Success:
print(response.result.value!)
//...
case .Failure:
//...
}
}
My web service returns the following JSON:
{
//...
"InvoiceLines": [{
"Amount": 0.94
}]
}
Alamofire is treating this as a double instead of a decimal so in the output console I get:
{
//...
InvoiceLines = (
{
Amount = "0.9399999999999999";
}
);
}
This then causes rounding errors further down in my code.
I've used Fiddler on the server to inspect the web service JSON response to confirm that it is returning 0.94. So from that I can rule out the server being the issue and suspect the responseJSON
causing my issue.
How can I get currency values to return as the correct NSDecimalNumber
value?
Extra information after Jim's answer/comments:
var stringToTest = "{\"Amount\":0.94}"
var data = stringToTest.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var object = try NSJSONSerialization.JSONObjectWithData(data!, options: opt)
var a = object["Amount"]
print(a) //"Optional(0.9399999999999999)"
var b = NSDecimalNumber(decimal: (object["Amount"] as! NSNumber).decimalValue)
print(b) //"0.9399999999999999"
If I pass through the value as a string in the JSON I can then get my desired result:
var stringToTest = "{\"Amount\":\"0.94\"}"
var data = stringToTest.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var object = try NSJSONSerialization.JSONObjectWithData(data!, options: opt)
var c = NSDecimalNumber(string: (object["Amount"] as! String))
print(c) //0.94
However I don't want to have implement changes to the API so need a solution which keeps the JSON in the same format. Is my only option to round the double each time? It just seems feels like the wrong way to do things and potentially raise rounding problems in the future.