How to add decimal numbers

I am trying to create a form that adds numbers to two decimal points. That is, to be able to add 5.5 from 105.67 from 12.54 and get: 123.71

That's how pleased I am, but when I try to add .toFixed (2), it either just does the inputs, not the general one ...

I am very new to Javascript, so just find a way in mo

Here is my jsfiddle: https://jsfiddle.net/Vicky1984/Lpwcuyb5/d

Here is the 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;
 }

early

+4
source share
1 answer

parseFloat()will return floating point numbers. ex. 1, 0, -2, 3.3, 505.1236

parseInt()will return the integers ex integers. -1, 0, 1, 2, -59635

Use parseFloat()

BTW, , qty2

FIDDLE

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>
Hide result
+2

Source: https://habr.com/ru/post/1671607/


All Articles