JSONSerialization formatting of Double

Hi,


I encountered a formatting problem during serialization of an object to JSON. Example code is


do {
  let double = Double(1.23)
  print(double)
  let json = try JSONSerialization.data(withJSONObject: ["double" : double])
  print(String(data: json, encoding: .utf8)!)
} catch {
  print(error.localizedDescription)
}


and the printed result on the command line is


1.23
{"double":1,23}


So directly printing the double value uses a "." as decimal point (wanted behavior) but serialized to JSON it is using a ",". To make it even more confusing, if I debug the code within Xcode I am getting a "." decimal point for JSON too.


I tried changing the Locale in code, setting system settings to "." as decimal point, … all to no avail. Does anyone have an idea?

Replies

What platform are you targeting? And if it’s macOS, what type of project?

By way of reference, I changed my iOS simulator to German and it doesn’t reproduce the problem you’re seeing (both lines of output contain “1.23”). Just to be sure I had the locale settings right, I added the following line of code and it prints “1,23”.

print(NumberFormatter.localizedString(from: double as NSNumber, number: .decimal))

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"