• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arithmatic calculations using Big Decimals

 
Huma Rangwani
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 10091
56
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic