0

I tried to add value price tag several selects but I get some strange results. I would appreciate help to know that certain numbers do not sum well. Here I leave the link to the example jsfiddle.net http://jsfiddle.net/pgy74r1k/

javascript Function:

sumValues('#priceList', '#totalPrice');
function sumValues(list,total){
  var allListElements = $( "select" );
  var sum = 0;
  $( list ).find( allListElements ).each(function() {
    sum += Number($('option:selected', this).attr('price'));
  });
  $(total).empty();
  $(total).append(sum+' €');

}

html Code:

<div id="priceList">    
  <select class="participant" name="price1" style="width: 100%" onchange="sumValues('#priceList', '#totalPrice')">
        <option value="0" price="0"> 0€ </option>
        <option value="1" price="10.62" selected="selected"> 10.62€ </option>  
  </select>  
  <select class="participant" name="price2"
 style="width: 100%" onchange="sumValues('#priceList', '#totalPrice')">
         <option value="0" price="0"> 0€ </option>
         <option value="1" price="13" selected="selected"> 13€ </option>  
  </select>   
</div>      
<strong id="totalPrice"></strong>
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 1
    If you try running `13+10.62` directly, you'll see the strange result has nothing to do with your HTML or DOM scripting. Your issue is caused purely by how floating point math works, which is addressed directly in [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – apsillers Oct 31 '14 at 16:47

1 Answers1

0

You can use toFixed() method:

$(total).append(sum.toFixed(2)+' €');

EDIT: well not sure what you call a strange result?!

A. Wolff
  • 74,033
  • 9
  • 94
  • 155