This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "regarding  bigdecimal.divide problem" Watch "regarding  bigdecimal.divide problem" New topic
Author

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
0.1
0.10
0.1

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

0.1000000000000000055511151231257827021181583404541015625
0.10
0.1

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

<a href="http://faq.javaranch.com/java/UseCodeTags" target="_blank" rel="nofollow">Use Code Tags!!</a>
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38045
    
  22
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: http://aspose.com/file-tools
 
subject: regarding bigdecimal.divide problem
 
Similar Threads
BigDecimal vs double
What actual Double.toString(double d) does?
double decimal problems
wrong value
BigDecimal issue