Join GitHub today
GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together.Sign up
Normative: Make `JSON.stringify(-0)` preserve the sign #1466
Although JSON supports
This patch makes
Object.is(JSON.parse('-0'), -0); // → true (this is already the case, even without this patch) JSON.stringify(-0); // → '-0' Object.is(JSON.parse(JSON.stringify(-0)), -0); // → true
Mar 5, 2019
Under the following assumption – which is reasonable in many situations, and for which the relevant subset of Number values is expected to represent exactly the corresponding mathematical abstract concept of ”integer”:
I expect that
and, you guess it:
More generally, the distinction between +0 and -0 is primarily an artefact of the internal representation of numbers; the distinction between the two values is irrelevant for most purposes, and therefore should not surface in situations where you possibly don’t expect it.
JSON already surfaces it, though; it's just that
Note that the case of
Note that this discrepancy is not an innovation of
My sense of the rationale, without implying that all this was discussed explicitly, nor that there was general consensus on this rationale. The committee doesn't ask for consensus on rationale, just conclusions, on which we did agree.
A program that does not otherwise need to care about the difference between -0 and 0 should, as much as possible, be able to ignore this difference while remaining correct. After all, -0 and 0 denote the same real number. This is why (over my objections at the time), Map and Set key comparison is insensitive to the difference between -0 and 0.
The only places I am aware of where the programmer needs to be aware of the difference, if they do not otherwise care, is:
Most programs that do not otherwise care about the difference between -0 and 0 will also not care about the bullet points above. This is also a hazard, as these bullet points may violate the principle of least surprise. However, the first bullet is mandated by IEEE and ancient JS, necessitating the other bullets.
What about the situations where somebody does care about the distinction between
I can imagine a server/client exchanging messages, and that message might be
So is the recommendation in that case to completely avoid
It also seems odd that
referenced this pull request
Mar 12, 2019
Good point, thanks!
The decision was already made for String(-0) before my time. I am just trying to explain my sense of the rationale. Given the behavior of String(-0), I think the behavior of JSON.stringify(-0) must remain as is
Note that JSON also cannot directly represent