Hello, I would like to know how I can compute a math expression, contained in a string, in Javascript.
Example: calc = "(7*2+1)/2";
How could I calculate?
Hello, I would like to know how I can compute a math expression, contained in a string, in Javascript.
Example: calc = "(7*2+1)/2";
How could I calculate?
Using the eval method.
calc = eval("7*2+1/2");
Another example:
var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";
var res = a + b + c;
Using eval
, changing format does not influence anything.
Example:
var Variavel = 7*2+1/2; alert(Variavel);
Returns the same value as alert(eval("7*2+1/2"));
Only the value without quotes.