0

On my website I have a form like this:

<select id="payments" multiple="multiple">
  <option data-amount="23.1" value="1">Invoice 1</option>
  <option data-amount="25.3" value="2">Invoice 2</option>
  <option data-amount="50.0" value="3">Invoice 3</option>
</select>

And a little dash of Javascript:

$(function() {

    // Sum up and insert open_amount into 'amount' field depending on what invoice numbers are selected
    $("#payments").change(function() {
        var sum = 0;
        $('#payments :selected').each(function() {
            sum += Number($(this).data("amount"));
        });
        $("#payment_amount").val(sum);
    });

});

The problem is that I sometimes get weird numbers like 48.400000000000006 where I actually want rounded results with two decimal places.

How can I properly sum up all the selected amounts?

Tintin81
  • 9,821
  • 20
  • 85
  • 178
  • It's a common issue that float numbers are broken. Other languages give alternative solutions, such as decimal for c# and java but I found nothing for javascript. – user1835565 Jul 09 '14 at 11:54
  • I'm not sure of the general SO etiquette, but it's seems odd to mark this as a duplicate of a question that itself has been closed as a duplicate of another! Perhaps this should point to "[Is floating point math broken?](http://stackoverflow.com/questions/588004/)" – Scott Sauyet Jul 09 '14 at 12:05

4 Answers4

3

Use .toFixed(n) to format the decimal values.

 $("#payment_amount").val(sum.toFixed(2));
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
1

Use .toFixed(2) for two decimal points

$("#payment_amount").val(sum.toFixed(2));
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
1

use parseFloat() to convert it to a float then add it.

sum = sum + parseFloat($(this).data("amount"));

Then make it to 2 decimal points using .toFixed(2)

$("#payment_amount").val(sum.toFixed(2));
Krishanu Dey
  • 6,326
  • 7
  • 51
  • 69
0

it may be crazy but it will work:

parseFloat(48.400000000000006.toLocaleString())
A.T.
  • 24,694
  • 8
  • 47
  • 65