javaformulacalculatorbigdecimal

Calculate an expression in java which is accurate upto 19 digits


I have an expression in string for example formula="333333333333333333+222222222222222222" I am trying to calculate the value of the expression to be accurate upto 18 digits. to calculate I am using scriptEngine in java as the expression could be any expression however I am getting the result as 55555555555555552 Here is my code

ScriptEngineManager scriptEngineManager= new ScriptEngineManager();
ScriptEngine scriptEngine=scriptEngineManager.getEngineByName("JavaScript");
Object result=scriptEngine.eval(formula);

In object I get exponential to which I remove by converting to bigDecimal string. However the calculation is not accurate if I use scriptEngineManager. I also tried converting the numbers to big decimal by replacing all the numbers with 'new java.math.BigDecimal(number)' but still I get inaccurate value. Do I manually have to create a parser in which I add bigdecimals using their functions bigdecimal.add(bigdecimal) , however in that case I have to take care of BODMAS rule as well as it's an expression that I have to take care of.

Please help me how to calculate a string expression which is accurate upto 18 digits. Thanks in advance


Solution

  • So I was able to solve this by using an external library known as EvalEx. Maven link- evalExMvn. I was able to set the precision upto 18 digits and was able to evaluate the string expression.

    import com.udojava.EvalEx.Expression;  
    import com.udojava.EvalEx.Expression.ExpressionException;
    
     Expression expr = new Expression(formula);
     expr.setPrecision(18); // Set precision to 18 digits
     BigDecimal number= expr.eval();