# Arithmatic calculations using Big Decimals

Huma Rangwani

Greenhorn

Posts: 1

posted 4 years ago

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.

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.

posted 4 years ago

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

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

Winston

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

"Leadership is nature's way of removing morons from the productive flow" - Dogbert

Articles by Winston can be found here