Search code examples
javabigdecimal

JEP library with BigDecimal


I'm using the third-party library org.nfunk.jep. All calculations are in double within the library, regardless of which type the input variables had. So when the next code executes:

BigDecimal value1 = new BigDecimal("29250.24");
BigDecimal value2 = new BigDecimal("263.21");
JEP calc = new JEP();
calc.addVariable("var1", Double.parseDouble(value1));
calc.addVariable("var2", Double.parseDouble(value2));
calc.parseExpression("var1 - var2");
System.out.println("Result: " + calc.getValue());

I want result like "28987.03", but I get such a result:

Result: 28987.0300000002

Maybe someone knows how to work with this library in BigDecimal or knows some similar libraries that work with BigDecimal type?


Solution

  • First a repair:

    BigDecimal result = new BigDecimal(calc.getValue()).setScale(value1.getScale());
    

    One can take the resulting double and again place it in a BigDecimal. Special case: the scale for a multiplication would be the sum of the scales of both factors (0.1 * 0.1 = 0.01).

    A solution:

    Use the Java Scripting API. It exists for several languages, but the Java SE provides a JavaScript scripting which might suffice.

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");
    
        engine.put("var1", new BigDecimal("3.14"));
    
        try {
            engine.eval("print(var1.multiply(var1))");
            BigDecimal x = (BigDecimal) engine.eval("var1.multiply(var1)");
            double y = (Double) engine.eval("var1 * var1");
        } catch (ScriptException e) {
            e.printStackTrace();
        }