Reputation: 11
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
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
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