Search code examples
javabigdecimalmathcontext

Mathcontext needed for add, subtract and multiply?


first of, my search skills may be not as good as I hoped, so maybe this kind of question exists already. If so please tell me..

See this code below:

new BigDecimal("5").add(new BigDecimal("7"));

vs

new BigDecimal("5").add(new BigDecimal("7"), mathContext);

In which situations would I really need a mathcontext (except divisions)?

I never use a mathcontext unless I divide something. As far as I know this always worked, so what may be the drawbacks here? Do I need a mathcontext on add, subtract and multiply? I'm not so good into the BigDecimal, I simply want to use it to not lose any information like when using doubles. As I sometimes see code with mathcontext on adding something, I'm too afraid to just remove it only because it's my opinion that it is useless...


I read that question but didn't really find a proper answer to my specific question... I begin with BigDecimals without mathcontext and then calculate with them. So my question is, will I ever have drawbacks with this regarding information loss / precision etc? Or will this simply lead to maximum information and that's it?

Edit: I don't want to round, never. In cases of a division like 1/3 I would have to, of course, but in the cases of add, multiply and subtract I don't want any rounding. Do I then need a mathcontext in any circumstance?


Solution

  • If you are doing mathematical operations, that need rounding.

    If you add, subtract or multiply two numbers with some decimal parts and you would like to round the result, you also can use mathcontext.

    If you don't need to round anything, then you don't need it.

    So it is not only limited to avoid problems with endless rest from dividing like 1/3