Win a copy of Design for the Mind this week in the Design forum!

# Arithmatic calculations using Big Decimals

Huma Rangwani
Greenhorn
Posts: 1
Hi

I have a calculation using big decimal values x, y=7888 and z= 4902 as below:
x = (y * 1000 / z)
I get arithmatic error as "Non-terminating decimal expansion" without rounding up. But the required result is 1609.13913, where as with calculation below I am getting result as 1609.15200.
System.out.println(new BigDecimal("7888").multiply(new BigDecimal("1000").divide(new BigDecimal("4902"),5,BigDecimal.ROUND_HALF_UP)));
Even as I use:
System.out.println(new BigDecimal("7888").multiply(new BigDecimal("1000").divide(new BigDecimal("4902"),11,BigDecimal.ROUND_HALF_UP)));
The result is coming as 1609.13912686288.

Winston Gutkowski
Bartender
Posts: 10247
58
Huma Rangwani wrote:I get arithmatic error as "Non-terminating decimal expansion" without rounding up.

Which simply means that the result cannot be represented by a decimal number (which is quite often the case).

But the required result is 1609.13913, where as with calculation below I am getting result as 1609.15200.
System.out.println(new BigDecimal("7888").multiply(new BigDecimal("1000").divide(new BigDecimal("4902"),5,BigDecimal.ROUND_HALF_UP)));

And that's because your bracketing is wrong. In cases like this it's usually a good idea to write "dumb" code, and spread things out a bit, rather than piling everything together in one statement, viz:and now look at your statement:NOW do you see where the problem is?

Winston

 With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.