-3

I am trying to read a json file with swift and it contains a field with 0.97.

If I tried to cast the field to a float, it would return nil, but if I were to cast it to a double, it would return the correct value. However, the only difference I could find on double and float was that double is 64-bit while float is 32-bit. I am wondering what is causing the difference.

carrotzoe
  • 127
  • 1
  • 1
  • 8

2 Answers2

0

It's a known issue that casting Any to Float has issues. See previous discussion. Just cast to Double.

Mark S.
  • 3,849
  • 4
  • 20
  • 22
0

Seems to work for me:

var jsonString = "{\n" +
    "\"float\":0.97,\n" +
    "\"double\":0.97\n" +
    "}\n"

struct Outcome: Decodable {
    let float: Float?
    let double: Double?
}
let data = jsonString.data(using: .utf8)!
let outcome = try JSONDecoder().decode(Outcome.self, from: data)
print(outcome) // Outcome(float: Optional(0.97), double: Optional(0.97))
Samps
  • 799
  • 6
  • 12