JS Quirks: stringified numbers
When I was working on Node.js PR 9492, this comment
This should probably test for a wider range of values.
test/parallel/test-net-internal.js
has some good examples.
made me look at that file. As I was going through the test, few of the bad values were interesting. I normally test with stringified positive decimal numbers and negative decimal numbers. But I saw stringified negative octal, binary, and hexa decimal numbers.
I got curious as I have never used them before, I just wanted to see their corresponding negative values. So I wrote a program like this
|
|
and I was expecting to see the result
but all I got was
The unary - operator simply negates the magnitude of the numbers. The stringified numbers were not processed in the same way as their number counterparts. So I looked at the ECMAScript specification’s ToNumber Applied to the String Type section (which is actually responsible for converting strings to numbers).
Only the StrDecimalLiteral
production allows signed numbers. If we look at the definition of others in the Numeric Literals section,
|
|
So, as per the specification, only the decimal numbers can have signs in the stringified number form. That is why the others are not considered as numbers.