简体   繁体   English

使用javascript添加计算器

[英]add calculator using javascript

I have used this code for numeric addition. 我已将此代码用于数字加法。 The only one problem is that it is not calculating expressions like (10 + 1.5 = 11 ). 唯一的问题是它没有计算像(10 + 1.5 = 11)这样的表达式。 Why this code not calculating .5 value in total? 为什么此代码不计算总计0.5值?

      <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 : 因为您正在使用parseInt()将其转换为整数,所以请尝试parseFloat

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

Here is demo 这是演示

parseInt() rounds off the decimal values hence not included in calculation. parseInt()舍入十进制值,因此不包括在计算中。 if you want to consider decimal into calculation then you must use parseFloat() 如果要在计算中考虑小数,则必须使用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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM