Reputation: 33
Is there any way to set a format of double values when I create JSON with NSJSONSerialization?
For example:
let dict :Dictionary<String,NSNumber> = ["key1" : 75.01, "key2" : 80.93, "key3" : 79.07, "key4" : 79.10 ]
let JSONData = try! NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted)
let JSONText = NSString(data: JSONData, encoding: NSASCIIStringEncoding)
NSLog("JSON string = \(JSONText!)")
I get the following output:
JSON string = { "key1" : 75.01000000000001, "key2" : 80.93000000000001, "key4" : 79.09999999999999, "key3" : 79.06999999999999 }
I would like to avoid these 000001, 0999999, etc. Thanks in advance.
Upvotes: 2
Views: 5370
Reputation: 70113
Use "Float" instead of "NSNumber":
let dict: Dictionary<String,Float> = ["key1" : 75.01, "key2" : 80.93, "key3" : 79.07, "key4" : 79.10 ]
Result:
JSON string = { "key1" : 75.01, "key4" : 79.1, "key2" : 80.93, "key3" : 79.07 }
Upvotes: 2