1

Possible Duplicate:
Why can't I access a property of an integer with a single dot?

I was reading an article, and came across the strange behaviour of javascript toFixed method. I don't understand the reason for the last statement. Can anyone explain please?

(42).toFixed(2); // "42.00" Okay

42.toFixed(2); // SyntaxError: identifier starts immediately after numeric literal

42..toFixed(2); // "42.00" This really seems strange

Community
  • 1
  • 1
Anshu
  • 7,783
  • 5
  • 31
  • 41

2 Answers2

5

A number in JavaScript is basically this in regex:

[+-]?[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?

Note that the quantifiers are greedy. This means when it sees:

42.toFixed(2);

It reads the 42. as the number and then is immediately confronted with toFixed and doesn't know what to do with it.

In the case of 42..toFixed(2), the number is 42. but not 42.. because the regex only allows one dot. Then it sees the . which can only be a call to a member, which is toFixed. Everything works fine.

As far as readability goes, (42).toFixed(2) is far clearer as to its intention.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
3

The dot is ambiguous: decimal point or call member operator. Therefore the error.

42..toFixed(2); is equivalent to (42.).toFixed(2)

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169