2012-11-24 82 views
0

可能重複:
Is JavaScript’s Math broken?爲什麼數量等於10時價格不正確?

從這樣一個問題: get all the input value and make an addition

有促銷:

買1每片價格爲14.37,買入10價格是13.28,買20每個價格是10.78 .....

現在我想做一個計數器。 http://down123.xxmn.com/count.htm

櫃檯寫下了整個價格。現在,我的代碼出了問題。

如果我在輸入框中填入5,然後在另一個輸入框中填入5。整個價格不是132.8。爲什麼?

如果我在輸入框中刪除一個數字,整個價格不會改變。謝謝

代碼:

var $inputs = jQuery('.liste_couleur_qty li input'); 
$inputs.keyup(function() { 
    var result = 0; 
    $inputs.each(function(){ 
    result += parseInt(this.value, 10); 
    }); 
    var JsonData =[{"price_id":"1","website_id":"0","price_qty":1,"price":"14.37"}, 
{"price_id":"2","website_id":"0","price_qty":10,"price":"13.28"}, 
{"price_id":"3","website_id":"0","price_qty":20,"price":"10.78"}, 
    {"price_id":"3","website_id":"0","price_qty":50,"price":"9.23"}, 
    {"price_id":"3","website_id":"0","price_qty":100,"price":"7.91"} 
] 
    var sorted = JsonData.sort(function(a,b){return a.price_qty - b.price_qty;}); 

var i=0; 
while(i < sorted.length && sorted[i].price_qty <= result){i++;} 

var price = sorted[i-1].price; 

    price= price*result; 

    jQuery('#qtyvalue').html("Total price is " + price);  
}); 

現在,當數量爲9,合適的價格是9 * 14.37。但我的櫃檯不對。

+0

你在說爲什麼顯示129.32888888888888而不是129.33?或者是別的什麼? – Abhilash

+0

yes.you – stackoverflow002

+0

nope,如果我在輸入框中刪除一個數字,整個價格不會改變 – stackoverflow002

回答

0

你正在尋找的答案是一個叫.toFixed()

試着改變,設置你的價格最後一行

jQuery('#qtyvalue').html("Total price is " + price.toFixed(2)); 

方法和應該工作。


更新

當你空的文本框,你的代碼將停止,因爲價值是工作''而非0,並且不能被添加。將代碼的第5行更新爲:

result += parseInt((this.value === '' ? 0 : this.value), 10); 
+0

好的,謝謝。如果我在輸入框中刪除一個數字,整個價格不會改變。謝謝 – stackoverflow002

+0

你的意思如下:jQuery('#qtyvalue')。html(「總價格是」+價格); }); – stackoverflow002

+0

不,在具有'.keyup()'的代碼行下面。在你顯示的代碼中,它會在第二行 – Abhilash