Pergunta

I have used this code for numeric addition. The only one problem is that it is not calculating expressions like (10 + 1.5 = 11 ). Why this code not calculating .5 value in total?

      <script>
      function calculate() {
       var myBox1 = document.getElementById('ORD_PRICE_1').value;    
       var myBox2 = document.getElementById('ORD_PRICE_2').value;
   var myBox3 = document.getElementById('ORD_PRICE_3').value;
       var result = document.getElementById('TOTAL');    
   var myResult = parseInt(myBox1) + parseInt(myBox2) + parseInt(myBox3);  
   result.value = myResult;


      }
     </script>
Foi útil?

Solução

because you are using parseInt() which convert it into integer, instead try parseFloat:

var myResult = parseFloat(myBox1) + parseFloat(myBox2) + parseFloat(myBox3);  

Here is demo

Outras dicas

parseInt() rounds off the decimal values hence not included in calculation. if you want to consider decimal into calculation then you must use parseFloat()

It should be like this.

 <script>
      function calculate() {
       var myBox1 = document.getElementById('ORD_PRICE_1').value;    
       var myBox2 = document.getElementById('ORD_PRICE_2').value;
   var myBox3 = document.getElementById('ORD_PRICE_3').value;
       var result = document.getElementById('TOTAL');    
   var myResult = parseFloat(myBox1) + parseFloat(myBox2) + parseFloat(myBox3);  
   result.value = myResult;


      }
     </script>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top