davdroman / PreciseDecimal

A Decimal type that plays nicely with literals and Decodable
The Unlicense
31 stars 2 forks source link

PreciseDecimal to JSON number ends up with long list of decimals #11

Open willthrom opened 1 year ago

willthrom commented 1 year ago

It seems from JSON to the PreciseDecimal we get the proper value but when writing back to JSON.... lots of decimal are added.

Not sure this is a problem for this library though. It is like the JSONEncoder ends up from PreciseDecimal to FLOAT to JSON-Number

image

Screen Shot 2022-11-10 at 12 06 05
davdroman commented 1 year ago

Yes, I'm afraid this is unavoidable because of how JSONEncoder is implemented. I'm planning a major release bump that moves away from literal numbers altogether and instead encodes decimals as strings by default. Details here #10.

It's really down to Apple to fix Decimal and the JSONSerialization APIs, but I wouldn't hold my breath for much longer at this point I'm afraid.

willthrom commented 1 year ago

It is surprising a back end produce a decimal point number and we cannot return back the same decimal value.

in this case backend is in golang, using the library Decimal, which JSONEncoder seems to do fine. Android seems to be able to parse properly this JSON from Decimal and the encode it back to send to the same backend.

But with Apple, reading breaks in some situations and although with your library now reading works most of the time (if not always), writing back to JSON Number creates those precision issues.

Here I can only see two possible options, or our back end do the truncate always (or rounding to the nearest), or we change FE<->BE to use strings instead, but that is a big change (besides network usage). I need to find some time to do some research because my initial finding have very almost none. (We are moving to from FE doing maths operations to MOVE everything to the BE, so no more desaligment between platforms)

davdroman commented 1 year ago

Here I can only see two possible options, or our back end do the truncate always (or rounding to the nearest), or we change FE<->BE to use strings instead, but that is a big change[^0]

You're correct. Although truncating/rounding is definitely the riskier choice.

[^0]: PS: I totally understand your discontent. It truly is ridiculous having this gap in the language in 2022 when Android solved it years ago.