Number Values Changing When ToString() Applied
Solution 1:
010 is treated as an octal notation because of the leading 0, as well as 0x10 will be treated as an hexadecimal notation. The octal numeral system uses the digits 0 to 7. Thus, 019 gives 19 because 9 is not an octal digit. Here some decimal numbers and their octal notations:
1 1 | 5 5 | 9 11 | 13 15
2 2 | 6 6 | 10 12 | 14 16
3 3 | 7 7 | 11 13 | 15 17
4 4 | 8 10 | 12 14 | 16 20
As you can see, since we have only 8 digits available (0, 1, 2, 3, 4, 5, 6, 7), 8 becomes 10 and 16 (8+8) becomes 20 (10+10). To make things even more clear, let's see how to count with 10 digits (as usual) then with 8 digits.
Using 10 digits:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, no more digits
nevermind, add 1 to the tenths and restart from 0
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, no more digits
nevermind, add 1 to the tenths and restart from 0
20, 21, etc...
Using 8 digits:
0, 1, 2, 3, 4, 5, 6, 7, no more digits
nevermind, add 1 to the "tenths" and restart from 0
10, 11, 12, 13, 14, 15, 16, 17, no more digits
nevermind, add 1 to the "tenths" and restart from 0
20, 21, etc...
The same applies to binary numbers:
0, 1, no more digits
10, 11, no more digits
100, 101, no more digits
110, 111, no more digits
1000, etc...
Let's compare with the decimal notation:
1 1 | 5 101 | 9 1001
2 10 | 6 110 | 10 1010
3 11 | 7 111
4 100 | 8 1000
Related stuffs: https://stackoverflow.com/a/32107058/1636522 :-)
Solution 2:
Number is a 64bit floating point representation of a number. It does not hold the digits as a array of characters so the leading zero is not available. String holds an array of characters and thus the leading 0 is not lost
JavaScript allows for transparent type conversion if possible thus the String "0111" == to the Number 111. So if you write the code "0111" == 111
it will return true.
Javascript provides two equality operators == and the strict equality === the second requires that both side are the same type so the Number(111) === String("111")
will return false as they are not the same type. The same applies for inequality operators != and !==
Post a Comment for "Number Values Changing When ToString() Applied"