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?