gopi gopi - 1 year ago 55
Javascript Question

what's the differences between (variable).toFixed(2) and +(variable).toFixed(2)?

I'm wondering what's the main differences between

(2.3444).toFixed(2) ==> 2.34


+(2.3444).toFixed(2) ==> 2.34

Both of them giving the same results. Can any one explain when I need to use that + sign?

Answer Source

The first gives you a string, the second gives you a (now truncated) number.

var x = 2.344;
var a = x.toFixed(2);
var b = +x.toFixed(2);
console.log(a, typeof a);
console.log(b, typeof b);

A unary plus will attempt to convert it's operand to a number.

The reason this matters is because the first one will lead to string concatenation if you "add" a number to it.

var x = 2.344;
var strNumber = x.toFixed(2);
console.log(strNumber + 5); // Expected: 7.34, actual: 2.345