-1

If I have a variable with the value "1+2+3", how can I convert this to a number? (in this case it would be 6)

This is my full code:


var screen = 0

function buttonActivation(button) {
    if (button == '=') {
        console.log(screen)
        var result = parseFloat(screen)
        document.getElementById('screenLine2').innerHTML = result
    } else if (screen == 0) {
        screen = `${button}`
    } else {
        screen = `${screen}${button}`
    }
    document.getElementById('screenLine1').innerHTML = screen
}

function clearScreen() {
    screen = 0
    document.getElementById('screenLine1').innerHTML = screen
    document.getElementById('screenLine2').innerHTML = ''
}

1 Answers1

1

What your title suggests is achievable with eval() function, but your question text is not clear. Also, this function has security risks that should be considered. Please consider alternative solutions.

var stringVariable = "1+2+3"
console.log(eval(stringVariable))
Masoud Tahmasebi
  • 423
  • 6
  • 22
  • please see [Never Use Eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval!). You should not provide a solution that you yourself pointed out that its a security risk – Yousaf May 17 '20 at 09:53