Wayniac Posted April 22, 2010 Share Posted April 22, 2010 The problem that I am having is in the field "total", its spitting out "40.3180.4". Where it should be 117.95, below are my calculations. quantity(10) * price(10) = subtotal(100) subtotal(100) * 0.0795 = tax(7.95) subtotal(100) * 0.1 = s&h(10) subtotal(100) + tax(7.95) + s&h(10) = total(117.95) <!-- Field Calculations --> <script> function f_sub_total(){ // Calculating Subtotal var _quantity = document.getElementById("quantity").value; if(!_quantity){ var _quantity = 0; } var _price = document.getElementById("price").value; if(!_price){ var _price = 0; } document.getElementById("sub_total").value = _quantity * _price; // Declare Local Variables var _sub_total = document.getElementById("sub_total").value; // Calculating Tax document.getElementById("tax").value = _sub_total * 0.0795; // Calculating S&H document.getElementById("sh").value = _sub_total * 0.1; // Declare Local Variables var _tax = document.getElementById("tax").value; var _sh = document.getElementById("sh").value; // Calculating Total document.getElementById("total").value = _sub_total + _tax + _sh; } </script> This is the Total outcome I get. Its adding the variables like strings. 100 + 7.95 + 10 Total: 1007.9510 PS: If you change the "+" signs to "*", they will multiply perfectly. Quote Link to comment Share on other sites More sharing options...
F1Fan Posted April 22, 2010 Share Posted April 22, 2010 Because JS uses the + sign to add numbers and strings together, you need to explicitly tell JS that your variables are numbers. Use the parseInt() and parseFloat() functions on each of your numeric variables to "convert" them to what JS know is a number, not a string. Quote Link to comment Share on other sites More sharing options...
Wayniac Posted April 22, 2010 Author Share Posted April 22, 2010 I tried this, but then all my JS code stopped working... clearly I made a mistake... Any suggestions for my syntax? document.getElementById("total").value = parseFloat(“_sub_total + _tax + _sh”); Quote Link to comment Share on other sites More sharing options...
F1Fan Posted April 22, 2010 Share Posted April 22, 2010 What you did basically just tried to do a parseFloat after the string addition. Try this: document.getElementById("total").value = parseFloat(_sub_total) + parseFloat(_tax) + parseFloat(_sh); For reference: http://www.w3schools.com/jsref/jsref_parsefloat.asp Quote Link to comment Share on other sites More sharing options...
Wayniac Posted April 22, 2010 Author Share Posted April 22, 2010 That worked perfectly, thank you very much. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.