New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add ability to serialise Decimal as string #600
Comments
To be clear, the expected behaviour is: >>> ujson.dumps(decimal.Decimal("1.123123123123123123123123123"))
'"1.123123123123123123123123123"' i.e. the output is a JSON string and there's no rounding? |
And setting the |
Current behaviour:
Expected behaviour:
|
I would argue that the dumping behaviour is correct. Numbers in JSON are not floats but arbitrarily long sequences of digits. For parsing, we should support |
Honestly, I'd rather delete the current handling of |
I disagree. The current implementation is definitely not right though since it converts to a float first. This results in rounding and loss of number of significant figures. |
Some examples of what I would expect: >>> ujson.dumps(decimal.Decimal('1.230'))
'1.230'
>>> ujson.dumps(decimal.Decimal('1.23000000000000001'))
'1.23000000000000001'
>>> ujson.dumps(decimal.Decimal('0.123456789012345678901234567890'))
'0.123456789012345678901234567890'
>>> ujson.dumps(decimal.Decimal('-0'))
'-0'
>>> ujson.dumps(decimal.Decimal('-0.00'))
'-0.00'
>>> ujson.dumps(decimal.Decimal('1e1'))
'1E+1' # or equivalent; this is the Python 3.10 decimal normalisation behaviour |
I guess that if we went down the route of decimals written exactly as JSON numbers then we'd have to implement #401 or it's all a bit of a pointless exercise. Sod it, I don't mind which route we choose. |
It wouldn't be entirely pointless, but yeah, I agree we should implement that anyway (if only for compatibility with stdlib). I looked a bit into what would be needed for this. |
If you're worried about edge cases like infinity and negative zero, then as long as we have tests for them, I don't see any harm relying on |
Those edge cases are behaving. I can't think of anything that would produce weird output. I guess it just annoys me that it isn't documented, which means it shouldn't be relied on. Yeah, I'd add plenty of tests. |
I do find it weird that |
Fortunately, the former produces the output we want, and same for |
I read through the code I linked above. There's one special case: signalling NaNs would become |
The claim "Numbers in JSON are not floats but arbitrarily long sequences of digits." is a bit dubious. |
Currently Decimal serialises to floats by default, which is undesirable when working with money for instance. The
default
option cannot be used for this since it does not raise an error, so a clean way to be able to specify that Decimal should be serialised as a string indumps
would be very helpfulThe text was updated successfully, but these errors were encountered: