New course! Every coder should learn Generative AI!
Try a free lesson0
Can someone help me with this?
How can I store a mathematical operator inside a variable and then use the variable to do an equation?? (Im using kotlin) var Operator ="+" var num1 = 1 var num2 = 2 Print (num1 + operator +num2)
2 Answers
+ 4
Depends on where you run the code. There is eval function that is part of the JavaScript libraries. However, you can do like I did here and build your own expression parser. It limits the security risks of allowing eval to execute unknown code possibly hacking your program.
https://code.sololearn.com/cyC0L9ZsJ7y3
0
You Don't need to store operator in variable...operators are predefined in all programming languages...just put relevant operator for your desired result.