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
A number in JavaScript is basically this in regex:
Note that the quantifiers are greedy. This means when it sees:
It reads the
42.as the number and then is immediately confronted withtoFixedand doesn’t know what to do with it.In the case of
42..toFixed(2), the number is42.but not42..because the regex only allows one dot. Then it sees the.which can only be a call to a member, which istoFixed. Everything works fine.As far as readability goes,
(42).toFixed(2)is far clearer as to its intention.