File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Arithmatic calculations using Big Decimals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Arithmatic calculations using Big Decimals" Watch "Arithmatic calculations using Big Decimals" New topic
Author

Arithmatic calculations using Big Decimals

Huma Rangwani
Greenhorn

Joined: Oct 09, 2012
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

Joined: Mar 17, 2011
Posts: 8657
    
  23

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


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Arithmatic calculations using Big Decimals