Float rounding (in JSON)

Sergey kornburn at yandex.ru
Fri Dec 30 21:34:37 UTC 2022


On Thursday, 13 October 2022 at 19:00:30 UTC, Sergey wrote:
> I'm not a professional of IEEE 754, but just found this 
> behavior at rounding in comparison with other languages. I 
> supose it happened because in D float numbers parsed as double 
> and have a full length of double while rounding. But this is 
> just doesn't match with behavior in other languages.

So there is no luck with std.json for me. But when std is not the 
solution, third party libraries could help. I've tried ASDF. This 
is kind of archived library, but it works well, its documentation 
is small and clear (mir-ion really needs to improve 
documentation).

So in asdf we could just serialize the json and it will 
automatically round numbers with the same **magic** logic for 
floating as other languages do.

The only thing: some numbers which are usually double could be 
presented in JSON as integers. Automatically asdf convert them to 
double too. In case you need to process them exactly as integers 
you could use Variant!(int, double) as a type of the data. And 
provide your custom serializer/deserializer as it is proposed in 
asdf documentation example.
http://asdf.libmir.org/asdf_serialization.html#.serializeToAsdf

PS Thanks to Steven for his suggestions in Discord.



More information about the Digitalmars-d-learn mailing list