truncated doubles getting long decimals in for loop in java
<p>I have two double values that are truncated to two decimal spots. Each one represents a spot on a radian circle, and they are either supposed to increment or decrement by <code>0.01</code> until they find a target value. Here's the code:</p>

<pre><code>    BigDecimal negPath = new BigDecimal(roundAndConvert(pendA.getTheta()));
    BigDecimal posPath = new BigDecimal(roundAndConvert(pendA.getTheta()));
    BigDecimal target = new BigDecimal(roundAndConvert(pendB.getTheta()));
    for (negPath = negPath; ((negPath.doubleValue() &gt; -0.01) &amp;&amp; (!negPath.equals(target))); negPath = negPath.subtract(new BigDecimal(0.01))) {}
    for (posPath = posPath; ((posPath.doubleValue() &lt; 6.29) &amp;&amp; (!posPath.equals(target))); posPath = posPath.add(new BigDecimal(0.01))) {}

//here's the method that rounds the values

public double roundAndConvert(double value)
{
        double holder = (int)(value*100) / 100.0;
        if (holder &lt; 0)
        {
            while (holder &lt; -6.28) {holder += 6.28;}
            holder += 6.28;
        }
        else
        {
            while (holder &gt; 6.28) {holder -= 6.28;}
        }
        return holder;
}
</code></pre>

<p>The problem that I'm having is that the two Path values are returning doubles with long decimals, like so:</p>

<pre><code>pos = 6.299999999999944
neg = -0.01999999999996656
</code></pre>

<p>The values that they return aren't like this before the for loop, so I think it has to do with the increment/decrement.</p>

<p>EDIT: tried replacing the doubles with BigDecimals, but now the program is freezing at the for loops. I see the stringCache for the Path values, and they still have the long decimals.</p>

<p>EDIT: Another change to the coding, this time using all <code>BigDecimal</code> objects and <code>equals</code> in the for loops, but I'm still getting long decimals.</p>

<p>EDIT: finally worked with the coding shown. The accepted answerer explains what I was doing wrong. Here's the code that works:</p>

<pre><code>    for (negPath = negPath; ((negPath.doubleValue() &gt; -0.01) &amp;&amp; (!negPath.equals(new BigDecimal((int)(target.doubleValue()*100)/100.0)))); negPath = negPath.subtract(new BigDecimal(0.01))) 
    {
        negPath = new BigDecimal((int)(negPath.doubleValue()*100)/100.0);
    }
    for (posPath = posPath; ((posPath.doubleValue() &lt; 6.29) &amp;&amp; (!posPath.equals(new BigDecimal((int)(target.doubleValue()*100)/100.0)))); posPath = posPath.add(new BigDecimal(0.01))) 
    {
        negPath = new BigDecimal((int)(negPath.doubleValue()*100)/100.0);
    }
</code></pre>
