0

I hava use jeval to get result from an expression string,but I find that sometimes I get the wrong result.So I try to use the BigDecimal,it is Ok,but if my express is more complex like (0.1+0.2)*10+15/3 How can I encapsulated into a function,do any jar or lib that have this function? The code is here:

 Evaluator eval = new Evaluator();
 String expression="(0.1+0.2)";
 String rest = eval.evaluate(expression);
 System.out.println(new BigDecimal(rest));  //0.30000000000000004

Here is my own function:

private String getResult(String expression){
  java.math.BigDecimal b = new java.math.BigDecimal("0.1");
  java.math.BigDecimal c = new java.math.BigDecimal("0.2");
  return b.add(c);
 }
flower
  • 2,212
  • 3
  • 29
  • 44
  • You need a pretty basic parser/evaluator, as is taught in university in first or second year. See also https://stackoverflow.com/questions/3422673/how-to-evaluate-a-math-expression-given-in-string-form –  Aug 18 '21 at 08:59
  • See this [Equation Solver](https://github.com/ggleblanc2/equation-solver) code for one way to create a parser / evaluator. – Gilbert Le Blanc Aug 18 '21 at 10:37
  • @Jean-ClaudeArbaut,using Javascript engine may be an option,but it can not solve the problem with floating-point math. – flower Aug 18 '21 at 15:24
  • There is more than one answer at this link. You may also implement Dijkstra's [shunting-yard algorithm](https://en.wikipedia.org/wiki/Shunting-yard_algorithm) (typical exercise), or use [Apache JEXL](http://commons.apache.org/proper/commons-jexl/), or any other existing package. I strongly suggest you implement it if you have never done this before: not difficult, and quite rewarding as you will be able to reuse the algorithm in many contexts. –  Aug 18 '21 at 16:10

0 Answers0