简体   繁体   English

如何添加带小数位的数字

[英]How do I add numbers with decimal places

I am trying to create a form that adds up numbers to two decmial points. 我正在尝试创建一个将数字加到两个decmial点的表单。 Ie be able to add up 5.5 with 105.67 with 12.54 and get: 123.71 即能够将5.5.6和105.67与12.54相加并获得:123.71

Here is as far as I've got, but when I try adding .toFixed(2) it either just does the inputs and not the total... 这是我所拥有的,但是当我尝试添加.toFixed(2)时,它只是输入而不是总数......

I'm very new to Javascript so just finding way at mo 我对Javascript很新,所以只是在mo找到方法

Here is my jsfiddle: https://jsfiddle.net/Vicky1984/Lpwcuyb5/d 这是我的jsfiddle: https ://jsfiddle.net/Vicky1984/Lpwcuyb5/d

Here is code I'm using; 这是我正在使用的代码;

function findTotal() {
  var arr = document.getElementsByName('qty');
  var tot = 0;

  for (var i = 0; i < arr.length; i++) {
    if (parseInt(arr[i].value))
      tot += parseInt(arr[i].value);
   }
  document.getElementById('total').value = tot;
 }

thanks in advance 提前致谢

parseFloat() will return floating point numbers. parseFloat()将返回浮点数。 ex. 恩。 1, 0, -2, 3.3, 505.1236 1,0,-2,3.3,505.1236

parseInt() will return whole number integers ex. parseInt()将返回ex的整数整数。 -1, 0, 1, 2, -59635 -1,0,1,2,5,93535

Use parseFloat() 使用parseFloat()

BTW, each id must be unique, so the second input is now qty2 顺便说一句,每个id必须是唯一的,所以第二个输入现在是qty2

FIDDLE 小提琴

SNIPPET SNIPPET

 function findTotal() { var arr = document.getElementsByName('qty'); var tot = 0; for (var i = 0; i < arr.length; i++) { if (parseFloat(arr[i].value)) tot += parseFloat(arr[i].value); } document.getElementById('total').value = tot; } 
 <div class="table"> <div class="row header"> <div class="cell"> Take Home Pay </div> <div class="cell"> Amount Per Month </div> </div> <div class="row"> <div class="cell"> Salary </div> <div class="cell"> <input placeholder="0.00" onblur="findTotal()" type="text" name="qty" id="qty1" /> </div> </div> <div class="row"> <div class="cell"> Overtime </div> <div class="cell"> <input placeholder="0.00" onblur="findTotal()" type="text" name="qty" id="qty2" /> </div> </div> <div class="row total-row"> <div class="cell"> Total Take Home Pay </div> <div class="cell" data-label="Monthly Income"> <input placeholder="0.00" type="text" name="total" id="total" /> </div> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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