When JSON encoding a Double there are too many decimal places
If you are trying to generate JSON and a double is encoded with loads of decimal places and weird “1” at the end, like this:
struct Coordinate: Encodable {
let latitudeInDegrees: Double
let longitudeInDegrees: Double
let accuracyInMeters: Double
}
let coordinate = Coordinate(latitudeInDegrees: 37.785834, longitudeInDegrees: -122.406417, accuracyInMeters: 5)
Generates JSON:
{
"coordinate" : {
"accuracyInMeters" : 5,
"latitudeInDegrees" : 37.785834000000001,
"longitudeInDegrees" : -122.406417
}
}
Change the type from Double
to Decimal
:
struct Coordinate: Encodable {
let latitudeInDegrees: Decimal
let longitudeInDegrees: Decimal
let accuracyInMeters: Decimal
}