swift-extras / swift-extras-json

JSON encoding and decoding without the use of Foundation in pure Swift.
Apache License 2.0
348 stars 15 forks source link

Maintaining precision with numbers #63

Open brianreinhold opened 4 years ago

brianreinhold commented 4 years ago

This is more of a question than a bug. I am trying to find a way to encode a decimal value with the proper precision. For example, with a precision of 1/1000, I want to encode 2.000 and not 2 or 2.0. The easy way would be to encode it as a string, but the FHIR spec requires that it be encoded as a number.

In Java I had access to a minimal JSON library where I had the option to encode the string sequence that would appear in the value even though the value itself was representing an integer.

In any case, is there a way I could encode a float. double, or Decimal value with the correct precision? What would it take to do it?

brianreinhold commented 4 years ago

Actually I have a hunch I know how to do it looking at the encoder code but I am so new to Swift and Xcode I wouldn't put too much on that. So I am trying to figure out how to import this source into a test XCode project.

fabianfett commented 4 years ago

Is this a duplicate of #64?

brianreinhold commented 4 years ago

Fabian,

In some sense yes. Though I am completely new to Swift and iOS, in Java the way that I was able to maintain precision was that I got a Java library that did not rely on your class variable names as providing the keys. IN the end I got the impression that the Encobable/Decoable protocol was forcing that (I may be wrong) which out the door meant it would not be possible to keep precision unless the class/struct itself did. In Java, there is a class 'BigDecimal' which DOES keep precision (though I did not use that).

But as I see it having the raw JsonValue and JsonObject and JsonArray classes works around the 'Codable' protocol allowing one to create JSON strings at a very basic level (so you can essentially pick and choose as you want). That solves the precision problem.

Brian


From: Fabian Fett notifications@github.com Sent: Monday, September 14, 2020 3:32 AM To: fabianfett/pure-swift-json pure-swift-json@noreply.github.com Cc: Brian Reinhold BrianReinhold@lnihealth.com; Author author@noreply.github.com Subject: Re: [fabianfett/pure-swift-json] Maintaining precision with numbers (#63)

Is this a duplicate of #64https://github.com/fabianfett/pure-swift-json/issues/64?

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHubhttps://github.com/fabianfett/pure-swift-json/issues/63#issuecomment-691875621, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AJMDO6YLG6YFFIPWSD2TVQLSFXBIPANCNFSM4RHRTN2A.