-1

i have a string with a math function, like "35+20". i want a new double variable that takes in the result of the math function i.e, 55.0 How do i achieve this? this is actually for android, i'm making a calculator..

blauge
  • 27
  • 3

3 Answers3

0

Manually parse the string and do a calculation at each operator symbol. It will get more complicated when dealing with brackets, however.

soundHippo
  • 23
  • 5
0

If you want to write it yourself, you'll probably want to implement the Shunting Yard Algorithm.

There are also some libraries that handle it for you.

https://github.com/uklimaschewski/EvalEx

Community
  • 1
  • 1
chessdork
  • 1,999
  • 1
  • 19
  • 20
0

Since you have mentioned you are working on a calculator I am assuming that you might not only be interested in just the + operation but on a bunch of other stuffs too. You can look in to open source GitHub project linked below which provides the JAVA implementation for the stuff you are trying to do https://github.com/uklimaschewski/EvalEx which can give you a good set of functionality that you desire. This project takes in a string as an expression and the returns the result in BigDecimal format. You can always extend it and tweek it to custom suite you needs.

Kowshick
  • 142
  • 3