1

Is there a way to configure JSONEncoder to add trailing decimal mark and zero when converting Double (whole number) to JSON?

Code below illustrates the issue.

import Foundation

struct NumberTest: Codable {
    let number: Double

    enum CodingKeys: String, CodingKey {
        case number
    }
}

let doubleNumber = NumberTest(number: 1.0)
let data = try? JSONEncoder().encode(doubleNumber)

print(String(data: data!, encoding: .utf8)!) // {"number":1}

Desired result would be {"number":1.0}.

1 Answers1

1

No, there is no (numeric) way.

JSON is just a platform independent lightweight data-interchange format and has only a single number format. 1 can be treated as Int or as Double / Float.

On the receiver side it can be formatted to any arbitrary format after deserialization.

vadian
  • 274,689
  • 30
  • 353
  • 361