my dog learned polymorphism*
The moose likes Java in General and the fly likes How to avoid rounding while BigDecimal division Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to avoid rounding while BigDecimal division" Watch "How to avoid rounding while BigDecimal division" New topic
Author

How to avoid rounding while BigDecimal division

Anand Kapadi
Greenhorn

Joined: Jan 15, 2004
Posts: 26
Hi,
I am trying to divide two BigDecimal numbers like this

BigDecimal startDateIndexPointValue = new BigDecimal(startDateIndexedValue.toString());
BigDecimal endDateIndexPointValue = new BigDecimal(endDateIndexedValue.toString());
// where startDateIndexPointValue = 2028, endDateIndexPointValue = 2047
BigDecimal intermediateValue;

intermediateValue = endDateIndexPointValue.divide(startDateIndexPointValue, 5, RoundingMode.HALF_UP);

The problem is that this using this precision and using the rounding mode, I am not getting the exact intermediate value.
I need the intermediate value for further calculation.
for e.g.
if I use windows calculator on these values

startDateIndexPointValue = 2028
endDateIndexPointValue = 2047
2047/2028 = intermediate value = 1.0093688362919132149901380670611

However, If i use the same values in BigDecimal division using the above rounding method,
i get the value of intermediate value as 1.00937

I cannot use RoundingMode.UNNECCESSARY, since BigDecimal division using this RoundingMode would throw a Runtime Arithmetic Exception.

Is there any way to avoid BigDecimal RoundingMode while division?
i.e. I do not want to perform any rounding for the intermediate value during division.

Thanks,
Anand



Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38483
    
  23
Unless you divide by a number whose prime factors only include 2 and 5, every division will recur, and go on to infinity. So you must round somewhere for BigDecimal for any number not a multiple of 2 and 5 only. 2048 is a multiple of 2 only, but 2047 isn't. so you must round. Choose a larger precision for your rounding.
Rama Krishna
Ranch Hand

Joined: Oct 16, 2007
Posts: 110
Campbell Ritchie wrote:Unless you divide by a number whose prime factors only include 2 and 5, every division will recur, and go on to infinity. So you must round somewhere for BigDecimal for any number not a multiple of 2 and 5 only. 2048 is a multiple of 2 only, but 2047 isn't. so you must round. Choose a larger precision for your rounding.


I guess, if you wanted the calculator's precision and scale, in BigDecimal you ask or specify, isn't it rather than setting the scale to a small value as 5.

Or did you find an alternative?

Regards
Krishna
 
Consider Paul's rocket mass heater.
 
subject: How to avoid rounding while BigDecimal division