Pascal dev
Pascal dev

Reputation: 11

How to convert a string with mathematical symbols into a number?

I'm trying to make a calculator with JS. Is there a way to convert a string like var calculation = "11+34*6" into a "number" so JS can print out the solution?

Upvotes: 1

Views: 1341

Answers (2)

Michael W. Czechowski
Michael W. Czechowski

Reputation: 3455

Use eval() function to solve your calculation even it is a string.

let calculation = '11+34*6';
let result = eval(calculation);

document.write(result);

For better understanding read the documentation on Mozilla Developer Network: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

Upvotes: 1

Alessio Cantarella
Alessio Cantarella

Reputation: 5201

You can use JavaScript eval function, that allows you to evaluate or execute a string argument, e.g.

console.log(eval("11 + 34 * 6"));

Upvotes: 1

Related Questions