Home > Software design >  How to change the value of .get().reduce( from parseInt to parseFloat
How to change the value of .get().reduce( from parseInt to parseFloat

Time:08-29

I am doing a mini system that will automatically compute the sum of the inputted floated numbers (1,124.35, 20,345.45 etc.) that will not round of the number (fix as it is as it compute the sum.

The result should be infloat and can take up to thousands format.

Ex. TOTAL: 24,345.25

jQuery($ => {

  const $expenses_debit = $(".expenses_debit"); //PS: Use a more specific selector than this one
  const $res_debit = $("#result_debit");

  $expenses_debit.on("input", () => {
    const total = $expenses_debit.get().reduce((acc, el) => (acc  = parseInt(el.value, 10) || 0), 0);
    $res_debit.text(total);
  });
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
    <tr>
        <td>Due to BIR</td><td> <input type="number" ></td>
    </tr>
    <tr>
        <td>Advances for Operating Expenses</td><td> <input type="number" ></td>
    </tr>
    <tr>
        <td>Advances to Special Disbursing Officers</td><td> <input type="number" ></td>
    </tr>
    <tr>
        <td>TOTAL</td><td><output id="result_debit"></output></td>
    </tr>
</table>

CodePudding user response:

Instead of parseInt use parseFloat in reduce.

jQuery($ => {

  const $expenses_debit = $(".expenses_debit"); //PS: Use a more specific selector than this one
  const $res_debit = $("#result_debit");

  $expenses_debit.on("input", () => {
    const total = $expenses_debit.get().reduce((acc, el) => (acc  = parseFloat(el.value, 10) || 0), 0);
    $res_debit.text(total);
  });
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
    <tr>
        <td>Due to BIR</td><td> <input type="number" ></td>
    </tr>
    <tr>
        <td>Advances for Operating Expenses</td><td> <input type="number" ></td>
    </tr>
    <tr>
        <td>Advances to Special Disbursing Officers</td><td> <input type="number" ></td>
    </tr>
    <tr>
        <td>TOTAL</td><td><output id="result_debit"></output></td>
    </tr>
</table>

  • Related