Strange javascript addition problem

I have this code:

var totalAmt=0;
for (i in orders)
{
   order=orders[i];
   if (order.status !='Cancelled')
        totalAmt=totalAmt + order.amount;
}

But if i have 3 orders with amounts 3, 1, and 5, then instead of totalAmt being 9, i get 0315. So I think its adding the amounts together as strings instead of integars.

How do I fix this?

Answers:

Answer

order.amount is a string, and if one of the operands of the + operator is a string, a concatenation is done instead of a sum.

You should convert it to number, for example using the unary plus operator:

var totalAmt = 0, i, order; // declaring the loop variables
for (var i in orders) {
   order = orders[i];
   if (order.status !='Cancelled')
        totalAmt += +order.amount; // unary plus to convert to number
}

You could alternatively use:

totalAmt = totalAmt + (+order.amount);
totalAmt = totalAmt + Number(order.amount);
totalAmt = totalAmt + parseFloat(order.amount);
// etc...

Also you are using a for..in loop to iterate over orders, if orders is an array, you should use a normal for loop:

for (var i = 0; i<orders.length; i++) {
  //...
}

That is because the for...in statement is intended to be used for iterate over object properties, for arrays it may be tempting to use it, because seems to work, but it's not recommended since it will iterate over the object properties, and if you have extended the Array.prototype, those properties will be also iterated in addition to the numeric indexes.

Another reason to avoid it is because the order of iteration used by this statement is arbitrary, and iterating over an array may not visit elements in numeric order, and also it seems to be much more slower than a simple for loop.

If iteration order is not important, I personally like iterating backwards:

var i = orders.length;
while (i--) {
   //...
}
Answer

Use the parseFloat() or parseInt() functions to convert the string to the appropriate type.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.