Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inconsistent behavior from BigDecimal and MathContext

I am Seeing some strange behavior from BigDecimal When I do division using mathContext the output is different than when I do the division by directly providing the scale and rounding mode Here is an example that I think should provide the same output

public static void main(String...args){
    MathContext mc = new MathContext(3,RoundingMode.HALF_UP);
    BigDecimal four = new BigDecimal(4);
    BigDecimal three = new BigDecimal(3);
    System.out.println(four.divide(three,3,RoundingMode.HALF_UP));
    System.out.println(four.divide(three,mc));
}

Output:

1.333
1.33

It appears that the scale is treated differently when using MathContext. Or I dont understand when to use which.

like image 977
thermite Avatar asked Dec 06 '25 09:12

thermite


1 Answers

The divide method of BigDecimal lets you specify the scale of the result, which loosely speaking is number of decimal places. scale = 3 means that a number will be expressed with 3 decimal places. A negative scale indicates the number of insignificant zeroes at the end of a whole number - so for example to round to the nearest 1000, you can specify scale = -3.

four.divide(three,3,RoundingMode.HALF_UP);  // scale = 3, so round to 3 decimal places

But a MathContext is different. It lets you specify precision - that is, the number of significant digits. This is different from scale.

MathContext mc = new MathContext(3,RoundingMode.HALF_UP);
four.divide(three, mc); // precision = 3, so round to 3 significant figures
like image 109
Dawood ibn Kareem Avatar answered Dec 07 '25 23:12

Dawood ibn Kareem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!