File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes regarding  bigdecimal.divide problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "regarding  bigdecimal.divide problem" Watch "regarding  bigdecimal.divide problem" New topic

regarding bigdecimal.divide problem

suresh sai
Ranch Hand

Joined: Jul 16, 2007
Posts: 62
Hi all.,

I have a small ( or big) problem with BigDecimal. While dividing ,especilly with double values ,it`s giving the values that is rounded. Let us suppose, I have the following code.

BigDecimal amount = new BigDecimal(0.1);
BigDecimal size = new BigDecimal(1);

If I divide amount by size its giving 0.12 rather 0.1. Please help me How can I get rid of this..?

Thanks in Advace
Tom Johnson
Ranch Hand

Joined: May 11, 2005
Posts: 142
Firstly I suggest using the string constructor on big decimal. Anyway, how do you perform the divide? I tried the following:

My results were

If I change the code to use the double constructor of BigDecimal, I get the following results:


So I dont see how you got 0.12, can you post the full code?

<a href="" target="_blank" rel="nofollow">Use Code Tags!!</a>
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45429
Please post more details: I can't see how you can get 0.12 out of even the most imprecise double division of 0.1 / 1.

I tried what you describe and got 0.1000000000000000055511151231257827021181583404541015625, which is the result of imprecision in the double arithmetic. Note the difference between the two lines in this code snippet:It produces this result:

The result of dividing 0.1 by 1 in BigDecimal is 0.1000000000000000055511151231257827021181583404541015625
and if you use Strings you get 0.1

That might sort out your problem.

By the way: there is a static field ONE in the BigDecimal class which you might find useful.

I agree. Here's the link:
subject: regarding bigdecimal.divide problem
It's not a secret anymore!