0

Here is Array

Product Details = [{Amount: '49.95'}, {Amount: ''}]

Here is Javascript used:

function() {
  var prods = {{Product Details}}; // Product Araay
  var Amount = 0;
  var i, len;
  for (i = 0, len = prods.length; i < len; i++) {
    Amount += parseInt(prods[i].Amount);
  }
  return Amount;
}

============= Result ==============

NaN

2
  • 1
    you are trying to add a number to something that is not a number. Consequently your result will be NaN :) Commented Feb 3, 2020 at 18:12
  • Please show how you are using your code. Currently there are a number of syntax errors, which leads me to believe this is not actually the code you are running... Commented Feb 3, 2020 at 18:19

5 Answers 5

1
  • just default the value to 0 if its a falsy value.
  • also use parseFloat instead of parseInt because you have float values :)

var Details = [{Amount: '49.95'}, {Amount: ''}, {Amount: '15.25'}]

function sums () {
  var prods = Details; // Product Array
  var Amount = 0;
  var i, len;
  for (i = 0, len = prods.length; i < len; i++) {
    Amount += parseFloat(prods[i].Amount || 0);
  }
  return Amount;
}

console.log(sums())

Sign up to request clarification or add additional context in comments.

Comments

0

You are getting NaN as a result because you are calling parseInt on an empty string for the second element, which returns NaN. Adding anything else to NaN will still be NaN.

Comments

0

If you are using decimal numbers, you might want to use parseFloat() to keep the total exact.

products = [{ Amount: '49.95' }, { Amount: '12.32' }];

function sum() {
  let amount = 0;
  for (let i = 0; i < products.length; i += 1) {
    console.log(products[i].Amount);
    amount += parseFloat(products[i].Amount);
  }
  return amount;
}

Comments

0

There is unary + operator which can replace parseInt/parseFloat:

+'' === 0

Just for information, don't recommend to use it as it is less obvious.

Comments

0

If you notice your array's second element has {Amount: ''}. parseInt('') results in NaN, and any more math operations on NaN with result in NaN.

To avoid this, you can change the code to Amount += parseInt(prods[i].Amount) || 0; Else you can use the unary + operator.

The fastest way to convert a string to a number in JavaScript is to use the unary + operator, which works for floating point numbers as well.

Amount += +prods[i].Amount;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.