Execute mathematical operation of a string and return the result [duplicated]

1

I tried to do it but I can not find how to do it, at a certain moment in the JavaScript I get a string of type (4+5)/2 and I want to get this operation.

Try using parseFloat do not recognize symbols like + or ( so tell me that that is not a number.

    
asked by Daniel 15.12.2017 в 19:22
source

3 answers

3

You can build a function that evaluates each element of your string. In case parseFloat only parse numbers.

function evaluaArimetica(fn) {
 return new Function('return ' + fn)();
}
console.log( evaluaArimetica('12/5*9+9.4*2') );
    
answered by 15.12.2017 в 19:29
1

You can use the eval JavaScript function.

alert(eval("(4+5)/2"))
    
answered by 15.12.2017 в 19:31
1

You can use the function eval ()

  

The eval () function evaluates a JavaScript code represented as a string (string), without referencing a particular object.

Syntax

eval(cadena de caracteres o string)

Parameters

  

string of characters (string)   A string of characters that represents an expression, statement or sequence of statements in JavaScript. The expression can include variables and properties of existing objects.

Returned or returned values

  

The value that results from the evaluation of the provided code. If this value is empty. undefined (article in English) is returned.

console.log(eval("(4+5)/2"))

Do not use eval unnecessarily

  

eval () is a dangerous function, which executes the code which is passed with the privileges of the caller. If you run eval () with a string of characters that could be affected by a malicious element, you could end up executing malicious code inside the user's computer with the permissions of your page or web extension. More importantly, a part of the third party code could access the scope in which eval () was invoked, which may allow entry to possible attacks in ways that the Function constructor (art in English) which is similar It is not susceptible.

     

eval () is generally also slower than other alternatives since it is invoked in the JS interpreter, while many other constructors are optimized by modern JS engines.

I hope you help greetings.

source: MDN

    
answered by 15.12.2017 в 19:51