Calling the toFixed method on a number literal [du

2019-01-28 22:50发布

问题:

This question already has an answer here:

  • Why can't I access a property of an integer with a single dot? 4 answers

When I call the toFixed() method on a decimal number literal like so:

var a = 67.678.toFixed(2);
console.log(a);

The result works and returns 67.68

However if I call the method on an integer - I get an error

var b = 67.toFixed(2);
console.log(b); // causes ERROR

Why is this the case?

NB:

If I save the integer number to a variable - the toFixed() method does work.

var c = 67;
c = c.toFixed(2);
console.log(c); // returns 67.00

See this jsBin

What is going on under the hood?

回答1:

var b = 67.toFixed(2); Simply generates a parsing error as the parser can't deduce that you meant it to be a number literal followed by a property accessor (Notice that the error is on the first line, not on the console.log(b))

The reason this works for 67.678.toFixed(2) is that there's no other option. The parser can deduce without ambiguity that the number literal ended at the "8" digit and can continue parsing the next dot as a property accessor (which causes boxing into a Number object first BTW).

A solution is obviously simple:

(67).toFixed(2);


回答2:

Your options include:

67 .toFixed(2)
(67).toFixed(2)
67..toFixed(2)
67.0.toFixed(2)
67["toFixed"](2)

All of these avoid the problem that the JS parser treats a dot immediately following a number as a decimal point.



回答3:

well Its a language related syntax issue. when you write xx. if xx is number it assumes the next thing to appear after the . operator is another number. but if you enclose it in parenthesis like (xx).toFixed(2) it works. what happens in a the back is an object after the parenthesis delimits the parse or when a full decimal literal is written is created and toFixed is called on that object.

Hope it answers our question.. :)