Wilson Wilson - 1 year ago 47
Javascript Question

Javascript is treating variables as Strings, why?

I have the variable y, which is a subtotal. Its value is different depending on what happens with the html, but throughout the script I declared it like this:

var y = 21.78;

etc. Why is it that on my last equation where I add up the total, it treats them as strings when I want to add the values?

var tax = (0.055*y).toFixed(2);
var totalprice = y+tax;
/* totalprice holds "21.781.20" instead of 22.98 */


According to:


toFixed() returns:

A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place.

thus, y+tax is cast to a string since one of the operands is a string.

In my opinion, this would make sense as Javascript's intrinsic numeric types do not have the ability to store a specific number of decimal place digits, so a string would be the most appropriate data structure to store this with.

I would advise you do all your addition before calling toFixed(), since the method is most suitable for formatting display output.

var taxRate = 0.055;
var subtotal = 21.78;

var tax = (taxRate * subtotal).toFixed(2),
totalprice = ((1+taxRate) * subtotal).toFixed(2);