Search code examples
javabigdecimalinteger-division

int divided by int to make a BigDecimal


Is it possible to divide two integers to make and make a BigDecimal out of it? I'm attempting to optimize my code. If I could reduce the number of times I declared a new BigDecimal, it should speed up my process significantly. As of now, the most I know I how to reduce my calculation is to:

BigDecimal tester = new BigDecimal("103993")
       .divide(new BigDecimal("33102"), 2000, BigDecimal.ROUND_DOWN);

I was wondering if it is possible to do something like this:

int example1 = 103993;
int example2 = 33102;

BigDecimal example3 = example1/example2;

Or something along those lines. My only goal is to speed up execution time.


Solution

  • There is a slight improvement that you can do that uses the BigDecimal's internal cache by using its valueOf method:

    BigDecimal.valueOf(example1).divide(
        BigDecimal.valueOf(example2), 2000, BigDecimal.ROUND_DOWN);