Jquery Bugs?? Long decimal number after two numbers multiply
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!
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).
I saw a google tech video about Java script, (the good parts). And there the guy was telling, that the number implementation in Javascript is not one of the good parts. It really sucks.
As far as I remember, Java script has only one type for a number. So there is no difference between Integer or Float. Hope that this will help.
精彩评论