微信小程序购物车产品计价:
问题:当选中商品,价格累加时会出现无限循环小数
解答:在计算前先parseFloat(变量),再计算的最后使用(变量).toFixed(2)保留两位小数
例如:
jiaCart:function(e){ var pid = e.currentTarget.id; var pic = parseFloat(e.currentTarget.dataset.pic); var cartList=this.data.cartList; var ex = false; for(var i=0;i<cartList.length;i++){ if(cartList[i].pid==pid){ cartList[i].num++; ex = true; } } if(!ex){ this.data.cartList.push({ pid: pid, num: 1 }); } var cartPics = (this.data.cartPic+pic).toFixed(2); this.setData({ cartPic:parseFloat(cartPics), cartNum:this.data.cartNum+1, cartList:cartList }); }, jianCart:function(e){ var pid = e.currentTarget.id; var pic = parseFloat(e.currentTarget.dataset.pic); var cartList=this.data.cartList; for(var i=0;i<cartList.length;i++){ if(cartList[i].pid==pid){ cartList[i].num--; if(cartList[i].num<=0){ cartList.splice(i,1); } } } var showCart=this.data.cartNum; if(showCart==1 && (this.data.cartNum-1)<=0){ this.setData({ showCart:0 }); } var cartPics = (this.data.cartPic-pic).toFixed(2); this.setData({ cartPic:parseFloat(cartPics), cartNum:this.data.cartNum-1, cartList:cartList }); }
|
请发表评论