0

In Chrome console, also test in edge and firefox

5.toFixed(2);

get

Uncaught SyntaxError: Invalid or unexpected token

in chrome.

SyntaxError: identifier starts immediately after numeric literal

in firefox.

Expected ';'

in edge.

But code below

5.1.toFixed(2);
(5).toFixed(2);

is ok in all three browsers above.

albert
  • 8,285
  • 3
  • 19
  • 32
Tshunglee
  • 337
  • 2
  • 11
  • 2
    because numbers ... try `5..toFixed(2)` as well ... – Jaromanda X Oct 28 '16 at 03:16
  • [_Return a String containing this Number value **represented in decimal fixed-point notation** with fractionDigits digits after the decimal point._](http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4.5) – Tushar Oct 28 '16 at 03:18
  • That code is ambiguous as to what the first "." stands for, either a decimal point for a float or a dot property separator. It is interpreted as a decimal point, so the identifier *toFixed* is unexpected. – RobG Oct 28 '16 at 03:23
  • @Tushar—it doesn't get that far, it's a syntax error. – RobG Oct 28 '16 at 03:25
  • As an aside, on those rare occasions when I see something like `5.1.toFixed(2)` in code my response is "Why?" Why not simply `"5.10"`? – nnnnnn Oct 28 '16 at 03:27

1 Answers1

1

This is because of the JavaScript parser assuming the dot in for example 5.toFixed(2) belongs the number literal. (As in 5., which is a valid number literal.) This is because JavaScript parses (at least number literals) greedily.

If you do (5).toFixed(2) however, it is clear to the parser what you want (the dot clearly is not a part of the number literal).

Same with 5.1.toFixed(2). The second dot clearly cannot belong to the number literal, so the parser has a better time with it.

hugabor
  • 75
  • 8