user2858545
user2858545

Reputation:

JavaScript concatenates numbers which should be counted up

<!DOCTYPE html>
<html>
<head>
<title>Sum of terms</title>
</head>
<body>
<script type="text/javascript">
var num = prompt("Sum of terms");
var result = (0.5 * num * (1 + num));
document.write(result);
</script>
</body>
</html>

This is a simple application that adds up all the terms of a serie of numbers (starting at 1). If num = 100, the result would be 5050. Instead, it gives me a result of 55000, this is because JavaScript concatenates the 1 and the 100 as 1100 (1 + num). How can I change the code so it will not concatenate the numbers but just counts them up?

Upvotes: 0

Views: 76

Answers (2)

Hanky Panky
Hanky Panky

Reputation: 46900

Make your num a numeric variable

num=parseInt(num);   // do this before you compute result.
                     // or even parseFloat if you need a FP value.

When you mix a number with a string then javascript will consider + as a concatenation operator. By casting it to an integer value you are making sure that JavaScript knows all the values in your equation are numeric and need to be treated as such.

Upvotes: 1

Marvin Brouwer
Marvin Brouwer

Reputation: 316

The problem is that prompt() returns a string, this results in javascript thinking you want to concatanate multiple strings. I would try:

    var num = prompt("Sum of terms");
    try{
        num = parseInt(num);
        var result = (0.5 * num * (1 + num));
        document.write(result);
    }
    catch(e){
        alert("Please specify a number");
    }

Upvotes: 1

Related Questions