0
몇 가지 값을 추가하려고 시도했지만 몇 가지 이상한 결과가 나타납니다. 특정 숫자가 합산되지 않는다는 것을 아는 데 감사하겠습니다. 여기에 내가 예에 대한 링크를 남겨 jsfiddle.net http://jsfiddle.net/pgy74r1k/복수 선택의 합계 값이 이상한 결과를냅니다.
자바 스크립트 기능 :
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 코드 : 미리
<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>
감사합니다.
$(total).append(sum.toFixed(2)+' €');
편집 :
'13 + 10.62'를 직접 실행하면 이상한 결과가 HTML 또는 DOM 스크립팅과 관련이 없음을 알 수 있습니다. 문제는 부동 소수점 연산이 어떻게 작동하는지에 따라 결정됩니다. [부동 소수점 연산이 깨졌습니까?] (http://stackoverflow.com/questions/588004/is-floating-point-math-broken)에서 직접 다루어집니다. – apsillers