Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Comparing values for decimal point accuracy

807606Mar 14 2007 — edited Mar 14 2007
Looping through calculations, I need to determine when a BigDecimal is accurate to a specific value (that is, stop when the BigDecimal < 10^&#8722;5.). Simplified example:
BigDecimal bd = new BigDecimal("0.0474271");
       do {  
       	       // various calculations to get a new value for bigdecimal, daft example is:
      	       bd.add(new BigDecimal("0.00000000001"));
        } while (??)
The condition for the do-while loop is: when bd is accurate to 10^-5 (having dusted off the old maths textbooks, apparently this is aka 1.0E-5 aka 0.00001 aka Math.pow(10.0, -5.0) ).

Having read through the API (very useful!) I've so far come up with the following solution for my while statement:
bd.compareTo (new BigDecimal("0.00001")) < 0
(Note that compareTo "returns: a negative number, zero, or a positive number if BigDecimal is numerically less than, equal to, or greater than 0".)

However, this stops at the second step in the loop... when I can plainly see from println step-statements that the BigDecimal still has a value very near to 0.0474271.

Can anyone point out what's going wrong here? Having read and reread my statements, looked through the logic, I just can't see for the life of me why this isn't working how it's supposed to (well, how I want it to... it's obviously my mistake because I don't think Java has "off" days lol).

Kate.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 11 2007
Added on Mar 14 2007
4 comments
1,066 views