문제

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>
도움이 되었습니까?

해결책

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

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

Here is demo

다른 팁

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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top