BigDecimal Rounding using power operator

Skip to first unread message

Joe Stiefel

Jul 9, 2021, 8:02:35 PM7/9/21
to Jep Java Users

I am evaluating this tool for an application I am writing. I require accurate representation that BigDecimal provides. I am running into a "java.lang.ArithmeticException: Rounding necessary" exception when trying to use the Power operator for some calculations, even though I passed in a "MathContext.DECIMAL64"(I believe this denotes "Half up" rounding to 16 places) to the BigDecComponents() constructor. Here is my code:

        Jep jep = new Jep( new BigDecComponents(MathContext.DECIMAL64));
        String math = ".1 ^ .2";
        Object evaluate = jep.evaluate();

I am aware that I can write my own power operator function, I am just curious why this tool does not use the rounding method associated with MathContext.DECIMAL64 or even any specified rounding passed in using other Mathcontext constructors.



Richard Morris

Jul 10, 2021, 3:12:32 AM7/10/21
to Jep Java Users
The problem here is in the java.math.BigDecimal class is really quite limited and only supports raising to integer powers

There are two methods


pow(int n)
Returns a BigDecimal whose value is (this^n), The power is computed exactly, to unlimited precision.


pow(int n, MathContext mc)
Returns a BigDecimal whose value is (this^n).

So there is no straightforward way to implement non-integer powers for big decimal.

There are some third party libraries that do provide implementations. See

As a general rule I would advise most people against using big decimals. There are a lot of pitfalls in using the library which is more geared towards financial calculations, there are better ways to  implement high precision see suggestions at

In the core Jep we want to not have dependencies on third party libraries. In the extensions package there is a Field framework that makes it easier to include third party libraries.
Reply all
Reply to author
0 new messages