1

So this is my code:

requestList.push(newDrink("Beer 1", 1.2, "Quantity:33cl", 0, "Beer"));

"1.2" is the price. And there's another variable that is initialized with 1 which is the "quantity".

function printtolist()
{
   var price = requestList[i].price * requestList[i].quantity;

   alert(price);
}

So, pretty easy, and when i add more quantity i print it, so in this case the output should be like this.

 1.2   
 2.4
 3.6
 4.8
 6
 7.2

But i'm getting this:

1.2
2.4
3.599999999999996
4.8
6
7.199999999999999

And I can't understand this. Quantity is added with

requestList[i].quantity++

So my variables are like "doubles and ints". Any ideas?

PhearOfRayne
  • 4,990
  • 3
  • 31
  • 44
Elsendion
  • 187
  • 1
  • 4
  • 15

1 Answers1

2

This is a problem with floating point arithmetic. Javascript cannot handle exact numbers. See this question for more details. However, since it appears that you're only using one decimal place, you can do this:

num=Math.round(num*10)/10;

Or as iccthedral pointed out in the comments, you can do this:

num.toFixed(1);

If you aren't going to do this, you shouldn't check if two numbers are equal with ==, but rather you should check it with this:

if(Math.abs(num1-num1)<=1e-6){
    alert("They are equal!");
}
Community
  • 1
  • 1
scrblnrd3
  • 7,228
  • 9
  • 33
  • 64