Jump to content

Can't add variables?


Wayniac

Recommended Posts

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.