4

enter image description here

the type of (8) and 8 are both numbers, but when called toString() method, (8) success but 8 failed, why?

python
  • 1,870
  • 4
  • 24
  • 35

2 Answers2

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"

enter image description here

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