title: Is there an equivalent for toPrecision() in Java?
body: <p>In porting an algorithm from JavaScript to Java, I've run into the problem that I need a replacement for JavaScript's toPrecision(). The problem is that I don't have a clue how small or large the numbers will be, so I can't use a simple NumberFormat with the right format.</p>
  
  <p>Is there a standard class that offers a similar functionality?</p>
  
  <p>EDIT
  Here is what I came up with:</p>
  
  <pre><code>   double toPrecision(double n, double p) {
          if (n==0) return 0;
  
          double e = Math.floor(Math.log10(Math.abs(n)));
          double f = Math.exp((e-p+1)*Math.log(10));
  
          return Math.round(n/f)*f;
      }
  </code></pre>
  
  <p>In principle, it does the right thing, but rounding errors completely ruin it. For example,
  <code>toPrecision(12.34567, 3)</code> returns <code>12.299999999999997</code></p>
  
  <p>EDIT 2
  This version works perfectly for 11 out of 12 test cases...</p>
  
  <pre><code>   double toPrecision(double n, double p) {
          if (n==0) return 0;
  
          double e = Math.floor(Math.log10(Math.abs(n)));
          double f = Math.round(Math.exp((Math.abs(e-p+1))*Math.log(10)));
          if (e-p+1&lt;0) {
              f = 1/f;
          }
  
          return Math.round(n/f)*f;
      }
  </code></pre>
  
  <p>But <code>toPrecision(0.00001234567, 3)</code> still returns <code>1.2299999999999999E-5</code> instead of <code>1.23E-5</code></p>