0

Good day. I am practising my javascript skills by making a small calculator. The problem I have encountered is that basically the variable called sum which contains the user input and is displayed on the page isn't displaying properly. It starts from zero.

When I add 2 I get 02 as an output. When I add 2 again insted of 4 I get 022. I am posting the entire source code below.

<!DOCTYPE HTML>
<head>
<title>Screw arround!</title>
<style>
    .btn{
        width : 50px;
        height:50px;
    }
    .btn2{
        width : 200px;
        height:50px;
    }
    .btn3{
        width : 200px;
        height:25px;
    }
</style>
</head>
<body>
    <center>
        <p id="asd"></p>
        <input type="number" id="textField" class="btn3"></input></br>
        <button id="add" onclick="compute(this.id)" class="btn">+</button><button id="subtract" onclick="compute(this.id)" class="btn">-</button>
        <button id="multiply" onclick="compute(this.id)" class="btn">*</button><button id="divide" onclick="compute(this.id)" class="btn">/</button></br>
        <button id="clear" onclick="compute(this.id)" class="btn2">Clear</button>

    </center>
</body> 

<script>
//----- variables
var sum = 0; // sum
var refr = document.getElementById("textField"); // get a referance to the textField

function compute(id)
{
    if(id === "add")
    { 
        sum += refr.value;;
        console.log(sum);
    }
    else if(id === "subtract")
    {
        sum -= refr.value;
        console.log(sum);
    }
    else if(id === "multiply")
    {
        sum *= refr.value;
        console.log(sum);
    }
    else if(id === "divide")
    {
        sum /= refr.value;
        console.log(sum);
    }

    //// set paragraph to the answer
    document.getElementById("asd").innerHTML = sum;
    if(id === "clear")
    {
        // make the values zero so new calculations can begin
        sum = 0;
        refr.value = '0';
        document.getElementById("asd").innerHTML = "";
    }
}
</script>

1 Answer 1

2

Try this in your compute function:

sum += parseInt(refr.value);

Or even parseFloat if you want:

sum += parseFloat(refr.value);

Note that value of input field is a string and +=value is actually string concatenation and not algebraic calculation

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

2 Comments

That is the answer. Thank you! I will mark it as the official answer after 10-15ish minutes (when the system will let me accept an answer)
Great! note that value is string and +=value is actually string concatenation and not algebraic calculation

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.