dougang1967 2010-04-24 01:14
浏览 70
已采纳

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

I am working on a shopping site and I am trying to calculate the subtotal of products.

I got my price from a array and quantity from getJSON response array. Two of them multiply

comes to my subtotal. I can change the quantity and it will comes out different subtotal.

However,when I change the quantity to certain number, the final subtotal is like

259.99999999994 or some long decimal number. I use console.log to check the $price and $qty. Both of them are in the correct format ex..299.99 and 6 quantity.I have no idea what happen. I would appreciate it if someone can help me about it.

Here is my Jquery code.

    $(".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**  

};

Thanks again!

  • 写回答

2条回答 默认 最新

  • drra6593 2010-04-24 01:25
    关注

    You almost have it, but .toFixed() returns the value, it doesn't set the value, for example of you did either of these it would appear correctly:

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

    Either set the variable to the .toFixed(2) value, or call the function when displaying (this is typically the most accurate, since rounding error not introduced earlier in the calculation).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛