Jquery Bugs ??两个数字相乘后的长十进制数

时间:2010-04-24 01:14:27

标签: php javascript jquery ajax json

我正在购物网站上工作,我正在尝试计算产品小计。

我从getJSON响应数组的数组和数量中得到了我的价格。其中两个相乘

来到我的小计。我可以更改数量,它会出现不同的小计。

但是,当我将数量更改为特定数量时,最终小计就像

259.99999999994或一些长十进制数。我使用console.log来检查$ price和$ qty。它们都是正确的格式ex..299.99和6 quantity.I不知道发生了什么。如果有人可以帮助我,我将不胜感激。

这是我的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**  

};

再次感谢!

2 个答案:

答案 0 :(得分:1)

你几乎拥有它,但是.toFixed() 返回值,它没有设置值,例如你做了其中任何一个出现正确:

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

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

答案 1 :(得分:-1)

我看到了一个关于Java脚本的谷歌科技视频(好的部分)。那家伙告诉我,Javascript中的数字实现不是好的部分之一。真的太糟糕了。

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

相关问题