Add operation with numbers

I wrote this code as part of a calculator for practice. It mainly works as intended.

However, the add operation combines two numbers instead of adding them. Why?

function calcApp (aNumber, bNumber) {
    var a = prompt("Enter A number :");
    var b = prompt("Enter B number :");
    var mathSign = prompt("Enter Math Sign :");

    aNumber = a;
    bNumber = b;

    if (mathSign == "+") {
        alert(a + b);
    }
    else if (mathSign == "-") {
        alert(a - b);
    }
    else if (mathSign == "*") {
        alert(a * b);
    }
    else if (mathSign == "/") {
        alert(a / b);
    }
    else {
        prompt("Enter a valid Math sign!!")
    }
}
calcApp();
+4
source share
2 answers

promptreturns a string. When you use the operator +for strings, they are concatenated.

You should get the numeric value of the user input. You can do this in various ways:

var str = '5.4';

console.log(parseInt(str, 10)); // parse integer from decimal numeric string
console.log(parseFloat(str));
console.log(+str);
console.log(Number(str));
Run codeHide result
+4
source

promptwill return a string. You need to convert it to a number.

You can use Numberan object to convert a string to a number.

Number, NaN (Not-A-Number). , Number('55 abc') NaN

, parseInt, . , parseInt ('12.99 ') 12.

Number ,

function calcApp (aNumber, bNumber) {
    var a = prompt("Enter A number :");
    var b = prompt("Enter B number :");
    var mathSign = prompt("Enter Math Sign :");

    aNumber = a;
    bNumber = b;

    //Convert to number
    a = Number(a); <----------
    b = Number(b); <----------

    if (mathSign == "+") {
        alert(a + b);
    }
    else if (mathSign == "-") {
        alert(a - b);
    }
    else if (mathSign == "*") {
        alert(a * b);
    }
    else if (mathSign == "/") {
        alert(a / b);
    }
    else {
        prompt("Enter a valid Math sign!!")
    }
}
calcApp();
+1

Source: https://habr.com/ru/post/1678951/


All Articles