1

I'm having a problem in calling the values I entered in the numberbox (I don't know what should I call it... if there's a textbox, there should be a numberbox. lol). If I enter "123456", the value of sum should be "21", but what happens is that the value of sum is "0123456".

<input type="number" name="user" id="input" maxlength="6" size="6" required>
<input type="button" onClick="Calculate()" value="Calculate">
<script type="text/javascript">
        function Calculate(){
            var user = [];
                user=document.getElementById("input").value;
            if(user.length==6){
                var sum=0;
                    for (i=0;i<user.length;i++){
                    sum=sum+user[i];
                    }
                  var ave=sum/6;
                    window.alert("Sum is: "+sum);
                    window.alert("Average is: "+ave);
            }
            else
                window.alert("Please input EXACTLY 6 numbers.");
        }
</script>
Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
  • You are looping for each number entered `123456` the default value of `sum` is 0 so in the first loop execution will place a `0` in front of the first array changing this to `01` – NewToJS Mar 17 '15 at 05:41
  • That is true, but his problem is not that there is a 0 in the front, but that he is concatenating a string together instead of adding. – m0meni Mar 17 '15 at 05:45
  • @AR7 correct, that isn't the only issue but it is the first problem with this function and since you have already submitted your answer for converting a string into an integer i didn't see much point in saying the same thing. I am also confused to why 123456 dividend by 6 would = 21..... 123456/6=20576. – NewToJS Mar 17 '15 at 05:47

1 Answers1

1

You are retrieving a string breaking it into parts and adding it back together.You need to convert the string into an integer first. To find out the multiple ways to do this, a very good answer on that is written here:

How do I convert a string into an integer in JavaScript?

sum = sum + parseInt(user[i],10);

Should work

Community
  • 1
  • 1
m0meni
  • 16,006
  • 16
  • 82
  • 141