Search code examples
macosfloating-pointdoubleswift4

Swift 4: Strange Double and Float behaviour


Basically the problem is that in this example:

let d1 = NSNumber(value: 1.4);
let d2 = d1.doubleValue;

let f1 = NSNumber(value: Float(1.4));
let f2 = d1.floatValue;

d1 results 1.4
d2 results 1.3999999999999999

f1 results 1.4
f2 results 1.3999999999999998

Does anyone know why is that?

I'm trying to parse JSON file like:

{"name": "something", "version": 1.4}

with the following code:

let json = try (JSONSerialization.jsonObject(with: someData) as? [String: Any])!;
let version: Double = (json["version"] as! NSNumber).doubleValue;

OR

let version: Double = json["version"] as! Double;

OR

let version: Double = json["version"] as! Float;

And I just can't get 1.4...

Rounding the number is not a solution for me, because I want to write back this number to JSON file, that will be parsed by other programs/languages and needs to be exactly 1.4 in the file.

Any suggestions?

UPDATE: The problem is only with 1.1 and 1.4. There is no problem with 1.2, 1.3, 1.5

UPDATE 2: Serialization code:

    let jsonDict: Dictionary<String,Any> = [
        "name" : name,
        "version" : version
    ];

    let data = try? JSONSerialization.data(withJSONObject: jsonDict, options: []);
    let jsonString = String(data:data, encoding:.utf8);

Solution

  • Ok, just to finalise the discussion.

    At the end Decimal type did the trick. So I changed all variable references to Decimal and NOT NSDecimalNumber, because I got error that it doesn't comply with Codable and Decodable protocols. Maybe there is a workaround for this, but the easiest solution is just to stick with Decimal.

    I would like to thanks to @JamesBucanek and @EricPostpischil for joining the discussion and help resolving this issue !!!