the type of (8) and 8 are both numbers, but when called toString() method, (8) success but 8 failed, why?
Asked
Active
Viewed 105 times
4
-
What do you get when you do `"8".toString(2)`? – Praveen Kumar Purushothaman May 02 '16 at 12:29
-
4when you cover a number with parenthesis then that would become an expression. – Rajaprabhu Aravindasamy May 02 '16 at 12:29
-
5give a space after 8 otherwise it will be treated as floating point – gurvinder372 May 02 '16 at 12:30
2 Answers
4
The difference between having 8
and (8)
is, the former is a plain number and the latter is a JavaScript Expression. The problem with the Exception is, the way you have written:
8.toString(2);
Here, the 8.
is treated as a floating point or decimal, which causes the syntax error. Since it takes it as a decimal, giving a decimal yields the right result:
» 8.0.toString(2);
« "1000"

Bergi
- 630,263
- 148
- 957
- 1,375

Praveen Kumar Purushothaman
- 164,888
- 24
- 203
- 252
2
8.toString() // Won't work
Here .
is treated as a floating point number representation. So if you want to convert a non floating point number into string just give a space after the number
8 .toString(); // Will work
And if it a floating point number then you can call toString
directly
8.2.toString(); // Will work even it doesn't have the space
8..toString(); // Will also work
But I would recommend you to use parenthesis for code readability.
And a number wrapped in parenthesis is an expression.

void
- 36,090
- 8
- 62
- 107