-2

Javascript

I'm getting 00.10.10.20.20.050.050.05 as my output. However, I want the sum which should be .75

var array = ['0.1','0.1','0.2','0.2','0.05','0.05','0.05']
var sum = 0;
function sumArray() {
    var random = Math.floor(Math.random() * 100);
    for (i=0; i < array.length ; i++) {
      sum +=array[i];
    }

}
sumArray();
alert(sum);
1
  • 4
    A string is not a number... Commented Oct 30, 2018 at 19:53

2 Answers 2

2

Actually you are concatenating strings (your array has strings on it). Just parse your strings:

var array = ['0.1','0.1','0.2','0.2','0.05','0.05','0.05']
var sum = 0;
function sumArray() {
    var random = Math.floor(Math.random() * 100);
    for (i=0; i < array.length ; i++) {
      sum += parseFloat(array[i]);
    }

}
sumArray();
alert(sum);
Sign up to request clarification or add additional context in comments.

Comments

-1

let array = ['0.1','0.1','0.2','0.2','0.05','0.05','0.05'];
let sum = array.reduce((a, b) => parseFloat(a) + parseFloat(b));
console.log(sum);

2 Comments

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
You're not using the same array as the question.

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.