Search code examples
javascripthtmlarrayscalculatorparseint

HTML/JavaScript Convert Strings to Numbers


I am doing a calculator for the freeCode challenge and im stuck with a problem: How to convert my input (string, all the equation) to a result? My code receives all the equation in a input field (example: 1+1 or 46+90) and i has to be able to solve the equation. What i want to do is put the first and the second numbers in two variables and convert them to int (maybe using parseInt to convert) and the operator will be put in other variable too. I orinally though in put all the equation in a array and take the numbers with a for+if statement. But how to do it? There is a better solution? Example: If i receive a equation 11+12, how to take the strings 1 and 1 and make 11? Same to 12..

My full running code: https://codepen.io/httxx/pen/bGRbKeQ

var trigger=0, x=0,y=0, operator=0;
function number(variable){
    if(trigger==0){
    x=variable;
    document.getElementById("display").value = ""+x;
    trigger=1;
    }else if(trigger==1){
    x=variable;
    document.getElementById("display").value += ""+x;
    }
}

function result(){
    var i;
    const val = document.querySelector('input').value;
}

function AC(){
    trigger=0;
    x=0;
    y=0;
    operator=0;
    document.getElementById("display").value = "0";
}

Solution

  • You can try split to split number and operator, then the string will be easier to handle.

    For example: inputString is equal to 11+12

    let result = 0;
    let stringArray = inputString.split(/[\+\-\*\/]+/);         \\ ["11", "12"]
    let firstNumber = parseFloat(stringArray[0]);               \\ 11
    let secondNumber = parseFloat(stringArray[1]);              \\ 12
    let operator = inputString.replace(/[0123456789.]/g, '');   \\ "+"
    switch (operator) {
        case '+':
             result = firstNumber + secondNumber;
             break;
        case '-':
             result = firstNumber - secondNumber;
             break;
        case '*':
             result = firstNumber * secondNumber;
             break;
        case '/':
             result = firstNumber / secondNumber;
             break;
    }
    

    Or you can just checkout this Build A Calculator With JavaScript Tutorial