Snubber
Snubber

Reputation: 1024

How would I create a math equation with strings?

Lets say I have the following variables (they're all strings):

x = "4"
op1 = "+"
y = "5"
op2 = "-"
z = "3"

How would I take these strings and make an equation that would give me the answer 6?

Upvotes: 0

Views: 743

Answers (3)

Nope
Nope

Reputation: 22339

One quick way you could do it in is using evil eval, similar to this:

var result = eval(x + op1 + y + op2 + z);

That will populate result with 6.


DEMO - Using evil eval


eval() is well suited for evaluating equations in string format. As eval() executes anything within the string passed you should look at validating/clean the data before before running eval() on it, specially in a public facing application.

Have a look at this SO post for an example on how to check the string is safe, in the context of equations, before using eval on it, assuming this it is something you have to worry about in your app.


Alternatives to eval()


While using eval() correctly and well managed is not the worst thing a non-eval() alternative would be great.

If you look at the comments on Shryme's own answer, there is an interesting way outlined. the interesting part of the comment is myOperator.execute(number1, number2);.


Why is eval evil?


eval() is not that special and is dangerous just or the same reason any other advanced language feature is dangerous when not understood and miss-used.

eval() is the most commonly used means of evaluating code at runtime.
Note that it executes code in a string in the scope within which it was called. It will blindly execute any malicious code!

eval() returns the result of the last evaluated expression. Hence if you execute several expressions only the result of the last one will be returned.

eval() is possibly the most miss-used short-cut and the cause of a lot of hours of debugging when it comes to scoping issues or results are not as expected when miss-used.

Upvotes: 1

Shryme
Shryme

Reputation: 1570

You can make a function that take 2 number and 1 operator, make a switch inside with the operator, do the math then return the result, then you recall the function with the result, your third number and the second operator and you have your answer

Upvotes: 0

user2925924
user2925924

Reputation: 45

Well, 4 + 5 - 3 would give you the answer 6. To use the strings into an equation, I believe you could do x + op1 + y + op2 + z? Make sure it is of type string

Upvotes: 0

Related Questions