title: How can I handle precision error with float in Java?
body: <p>I'm wondering what the best way to fix precision errors is in Java. As you can see in the following example, there are precision errors:</p>
  <pre><code>class FloatTest
  {
    public static void main(String[] args)
    {
      Float number1 = 1.89f;
      
      for(int i = 11; i &lt; 800; i*=2)
      {
        System.out.println(&quot;loop value: &quot; + i);
        System.out.println(i*number1);
        System.out.println(&quot;&quot;);
      }
    }
  }
  </code></pre>
  <p>The result displayed is:</p>
  <blockquote>
  <p>loop value: 11</p>
  <p>20.789999</p>
  <p>loop value: 22</p>
  <p>41.579998</p>
  <p>loop value: 44</p>
  <p>83.159996</p>
  <p>loop value: 88</p>
  <p>166.31999</p>
  <p>loop value: 176</p>
  <p>332.63998</p>
  <p>loop value: 352</p>
  <p>665.27997</p>
  <p>loop value: 704</p>
  <p>1330.5599</p>
  </blockquote>
  <p>Also, if someone can explain why it only does it starting at 11 and doubling the value every time. I think all other values (or many of them at least) displayed the correct result.</p>
  <p>Problems like this have caused me headache in the past and I usually use number formatters or put them into a String.</p>
  <p><b>Edit:</b> As people have mentioned, I could use a double, but after trying it, it seems that 1.89 as a double times 792 still outputs an error (the output is 1496.8799999999999).</p>
  <p>I guess I'll try the other solutions such as BigDecimal</p>