title: How can I get an accurate length of a BigInteger?
body: <p>I am trying to create a program which will generate numbers in the Fibonacci sequence until it finds a 1,000 digit number which is in the sequence. The code I have used runs fine and give a valid output, however, I have had trouble retrieving the length of each number; using <code>BigInteger</code> I have converted the <code>BigInteger</code> to a <code>String</code> and used the <code>String.length()</code> method to get the length, however, I have found that this is not giving the real length, and I can not see why.</p>
  
  <pre><code>import java.util.ArrayList;
  import java.math.BigInteger;
  public class problemTwentyFive {
    public static void main(String [] args) {
       ArrayList&lt;BigInteger&gt; fibonacciNumbers = new ArrayList&lt;BigInteger&gt;();
       boolean validNo = true;
       int x = 2;
       BigInteger tempAns = new BigInteger(""+0);
       fibonacciNumbers.add(new BigInteger(""+x));
       fibonacciNumbers.add(new BigInteger(""+x));
       do {
        tempAns = fibonacciNumbers.get(x-1).add(fibonacciNumbers.get(x-2));
        if (tempAns.toString().length() &lt;= 1000) {
           System.out.println(tempAns.toString().length());
           if(tempAns.toString().length() == 1000) {
              fibonacciNumbers.add(tempAns);
              validNo = false;
              break;
          } else {
             fibonacciNumbers.add(tempAns);
          }
        }
        x++;
        if (tempAns.toString().length() &gt; 1000) {
           validNo = false;
           break;
        }
        System.out.println(tempAns);
     } while (validNo == true);
     System.out.println("The first term in the Fibonacci sequence to contain 1,000 digits is term: " + fibonacciNumbers.size());
    }
  }
  </code></pre>
  
  <p>Is there a better way to get the length of a <code>BigInteger</code>? I have alread reffered to the question th<a href="https://stackoverflow.com/questions/18828377/biginteger-count-the-number-of-decimal-digits-in-a-scalable-method">BigInteger: count the number of decimal digits in a scalable method</a></p>
  
  <p><strong>Update</strong>
  Text text which is outputted after running the program is: </p>
  
  <pre><code>The first term in the Fibonacci sequence to contain 1,000 digits is term: 4781
  </code></pre>
  
  <p>We know this is false because if we look at the project I am attempting, when we input 4781 as the answer, it is incorrect. Click <a href="https://projecteuler.net/problem=25" rel="nofollow noreferrer">here</a> to view the project (<em>Project Euler - Problem 25</em>)</p>