加,减,除,乘小数

时间:2015-01-05 22:59:23

标签: javascript

对于JavaScript:

var add = function(calculate){
 var number1 =  document.getElementById('number1').value; 
  var number2 =  document.getElementById('number2').value; 
 document.getElementById('calculate').innerHTML= parseInt(number1) + parseInt(number2);
};

var subtraction = function(calculate){
  var number1 = document.getElementById('number1').value;
  var number2 = document.getElementById('number2').value;
  document.getElementById('calculate').innerHTML= parseInt(number1)  -  parseInt(number2);
};

var multiply = function(calculate){
  var number1 = document.getElementById('number1').value;
  var number2 = document.getElementById('number2').value;
  document.getElementById('calculate').innerHTML= parseInt(number1) * parseInt(number2);
};

var divide = function(calculate){
  var number1 = document.getElementById('number1').value;
  var number2 = document.getElementById('number2').value;
  document.getElementById('calculate').innerHTML= parseInt(number1) / parseInt(number2);
};

对于HTML:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="cool.css"/>
  <script src="calculator.js"></script>
  <body>
    <div id="box" style="width: 800px; height: 400px; border: 2px solid #000;">
        <div id="enter1">
        <p>Number 1: <input id='number1' value="ENTER 1"type="number"></p>
      </div>
      <div id="enter2">
        <p>Number 2: <input id='number2' type="number" value="ENTER 2"></p>
      </div>
      <button id="add"onclick='add()' style="font-size: 25px; background-color: #00B85C">ADD</button>
      <button id="sub" onclick='subtraction()' style="font-size: 25px; background-color: #FF6600;">SUBTRACT</button>
      <button id="multi"onclick='multiply()' style="font-size: 25px; background-color: #2E8AE6">MULTIPLY</buuton>
      <button id="div"onclick='divide()'  style="font-size: 25px; background-color: #CC6699;">DIVIDE</button>
      </div>
         <div id="box2" style="width: 800px; heigth: 600px; border 2px solid #000;">
         <p id='calculate'>ANSWER HERE</p>
       </div>
    </body>
   </head>
</html>

&#39;数字1&#39;和&#39; number2&#39;是HTML中输入标记的名称。我忘了插入&#39;计算&#39;作为参数;如果您认为没有必要,可以解释一下原因(这有助于我更多地了解代码;)

然而,

&#39;计算&#39;是我给段落标记的ID,答案将在其中显示。

我想用小数添加(不想写出其余部分)。现在,它只是添加整数。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

parseInt只返回整数值。您需要使用parseFloat

此外,使用parseInt时,最好传递一个基数值(例如parseInt(text, 10);)。 parseFloat不需要它。