Calling the toFixed method on a number literal [du

2019-01-28 23:07发布

This question already has an answer here:

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?

3条回答
太酷不给撩
2楼-- · 2019-01-28 23:24

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.. :)

查看更多
We Are One
3楼-- · 2019-01-28 23:32

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.

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-28 23:46

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);
查看更多
登录 后发表回答