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?
well Its a language related syntax issue. when you write
xx.
ifxx
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 andtoFixed
is called on that object.Hope it answers our question.. :)
Your options include:
All of these avoid the problem that the JS parser treats a dot immediately following a number as a decimal point.
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 theconsole.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 aNumber
object first BTW).A solution is obviously simple: