A simple function that parse json variable and returns a float.
func parseMyFloat(jsonString: String) -> Float? {
if let data = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: true),
let parsedJSON = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String : Any] {
if let parsedJSON = parsedJSON {
return parsedJSON["myFloat"] as? Float
}
}
return nil
}
Now if i try this.
print(parseMyFloat(jsonString: "{\"myFloat\":23.2322998046875}"))
// output: 23.2322998
output is fine but if I change 23.2322998046875
value to 23.2322998046
func returns nil.
print(parseMyFloat(jsonString: "{\"myFloat\":23.2322998}"))
// output: nil
Then I tried casting Any to Float which doesn't work.
let dic:[String : Any] = ["float1" : 23.2322998046875, "float2" : 23.2322998]
print(dic["float1"] as? Float) // prints nil
print(dic["float2"] as? Float) // prints nil
I have lots of float in my code, so after migrating to swift 4.1 I am having this issue.
Should I change all Float
's to Double
's ?? And 23.2322998046875
why works and why not 23.2322998
??