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>
3
  • 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 Commented Mar 17, 2015 at 5: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. Commented Mar 17, 2015 at 5: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. Commented Mar 17, 2015 at 5:47

1 Answer 1

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

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

1 Comment

Glad to hear it. Javascript is weird in that way since it lets you do so much weird stuff.

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.