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
https://forums.phpfreaks.com/topic/199421-cant-add-variables/
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
https://forums.phpfreaks.com/topic/199421-cant-add-variables/#findComment-1046640
Share on other sites

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

Link to comment
https://forums.phpfreaks.com/topic/199421-cant-add-variables/#findComment-1046660
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.