2010-04-24 156 views
1

我正在购物网站上工作,我正在计算产品的小计。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** 

}; 

谢谢!

回答

1

你几乎拥有它,但.toFixed()回报的价值,它不设置值,例如你是其中任一会正确显示:

newSub = newSub.toFixed(2); 
//or... 
console.log(newSub.toFixed(2)); 

要么设置可变为.toFixed(2)值,或者在显示时调用该函数(这通常是最准确的,因为在计算前面没有引入舍入误差)。

+0

男人......我知道我很接近!非常感谢!什么原因导致这种十进制计算错误任何人有想法? – FlyingCat 2010-04-24 01:30:41

+0

@Jerry - 这只是漂浮工作的方式,它不是一个精确的计算......这就是浮点精度。我不是在这里开玩笑,维基百科是获得这个主题的一个体面的理解的最好的地方:http://en.wikipedia.org/wiki/Floating_point – 2010-04-24 02:07:57

+0

行..我会检查出来..再次感谢。 – FlyingCat 2010-04-24 02:24:29

-1

我看到一个关于Java脚本的Google技术视频,(好的部分)。在那里,这个人告诉我,JavaScript中的数字实现不是好的部分之一。它真的很糟糕。

据我所知,Java脚本只有一种类型的数字。所以Integer或Float没有区别。希望这会有所帮助。

+0

据我所知..在Javascript中的Int和float之间存在差异。 ParseInt和ParseFloat为您提供不同的回报。谢谢你的信息。 – FlyingCat 2010-04-24 02:26:01

+0

@Jerry:一些函数和运算符(如'parseInt'和位运算符)将数字视为整数,但实际类型始终为64位浮点数。在某些情况下,JavaScript引擎可以在内部使用整数类型,但这绝对是一种优化。 – 2010-04-24 03:02:00