BigDecimal Scale and Calculations

I use BigDecimal to do the calculations. As a result of the calculation, I do:

 result.setScale(4, RoundingMode.HALF_UP); 

Using the .divide BigDecimal method requires scale and rounding, so now I do it like this:

 BigDecimal result = bigDecimal1.divide(bigDecimal2, 10, RoundingMode.HALF_UP); 

Therefore, I just use a scale large enough to make sure that the calculations are correct. But I'm not sure if this is the right way to do calculations using BigDecimal, and I doubt it ...

Therefore, any pointers are evaluated.

+4
source share
2 answers

You need to have a clear idea of ​​what you think is the right answer. If the error is less than 1e-10, then this is normal or it should be 1e-20 or 1e-30, etc. For a large separation result, you cannot get the exact result, because the result is presented as decimal.

BTW: if you need less than 15 significant digits, this is the precision of using double , and you may not need to use BigDecimal.

eg. 1/3 is considered 0.333333333 or 0.333333333333333333, but it will never be exactly correct (i.e. infinite in length)

+2
source

You are doing it right.

You can find several examples with BigDecimal on JavaPractices .

+1
source

Source: https://habr.com/ru/post/1386703/


All Articles