Search code examples
javaandroidscalebigdecimal

dividing bigdecimal containing bigger dividers than scale


I want to find a way to scale divisions of bigdecimals that can contain diverse numbers.

if I use this code:

r= x.divide(y,10, RoundingMode.HALF_UP);

the result of almost all results are correct, but if I have a divisor with more digits before point than the scale, the result is 0.0000000000.

What I have to do to obtain the correct precision on these divisions?

1 / 3 =0.3333333333 (scale 10)

1 / 151545545664651878 = 1.515455456646E-17 (for example)

100000000000000 / 3 = 3.3333333333E+14

thanks.


Solution

  • I found the way. It's realizing operations with mathcontext instead of scale. It seems that MathContext constructor uses precission not scale.

    with MathContext

    MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
    BigDecimal r = x.divide(y, mc);
    Log.i("mc","r = " + r);
    

    with Scale

    BigDecimal r = x.divide(y,10, RoundingMode.HALF_UP);   
    Log.i("scale","r = " + r);
    

    If I realize this division : 1 / 3333333333333333333333333 =

    The first output : 3.0000000000E-19 And the second output: 0E-10

    So, set Scale to a big decimal seems the same of Scale in MathContext but it isn't. I hope it could helps someone.