我正在购物网站上工作,我正在计算产品的小计。jquery错误两位数乘以后的长十进制数
我从getJSON响应数组的数组和数量中得到了我的价格。其中两人相乘
来自我的小计。我可以改变数量,它会出现不同的小计。
然而,当我改变量一定的数量,最终小计为像
259.99999999994或一些长十进制数。我使用console.log来检查$ price和$ qty。他们都在正确的格式EX..299.99和6数量。我不知道发生了什么。如果有人能帮助我,我将不胜感激。
这是我的JQuery代码。
$(".price").each(function(index, price){
$price=$(this);
//get the product id and the price shown on the page
var id=$price.closest('tr').attr('id');
var indiPrice=$($price).html();
//take off $
indiPrice=indiPrice.substring(1)
//make sure it is number format
var aindiPrice=Number(indiPrice);
//push into the array
productIdPrice[id]=(aindiPrice);
VAR URL =再次update.php
$.getJSON(
url,
{productId:tableId, //tableId is from the other jquery code which refers to
qty:qty}, productId
function(responseProduct){
$.each(responseProduct, function(productIndex, Qty){
//loop the return data
if(productIdPrice[productIndex]){
//get the price from the previous array we create X Qty
newSub=productIdPrice[productIndex]*Number(Qty);
//productIdPrice[productIndex] are the price like 199.99 or 99.99
// Qty are Quantity like 9 or 10 or 3
sum+=newSub;
newSub.toFixed(2); //try to solve the problem with toFixed but
didn't work
console.log("id: "+productIdPrice[productIndex])
console.log("Qty: "+Qty);
console.log(newSub); **//newSub sometime become XXXX.96999999994**
};
谢谢!
男人......我知道我很接近!非常感谢!什么原因导致这种十进制计算错误任何人有想法? – FlyingCat 2010-04-24 01:30:41
@Jerry - 这只是漂浮工作的方式,它不是一个精确的计算......这就是浮点精度。我不是在这里开玩笑,维基百科是获得这个主题的一个体面的理解的最好的地方:http://en.wikipedia.org/wiki/Floating_point – 2010-04-24 02:07:57
行..我会检查出来..再次感谢。 – FlyingCat 2010-04-24 02:24:29