title: Double number formatting in java
body: <p>I am working on a calculator program in Java and I need to display a number with no more than 15 digits in length (decimal point included).</p>
  
  <p>I've tried to format this number using <code>String.format("%g", myDouble)</code>, also with <code>%f</code>, but can't get the result I'm looking for.</p>
  
  <p>The thing is that I need the number:</p>
  
  <ul>
  <li>to be displayed as scientific notation if it has more than 15 digits,</li>
  <li>or display it without rounding it if it has less than 15 digits.</li>
  </ul>
  
  <p>Also, I do not want any fixed number of digits before or after the decimal point.</p>
  
  <p>Any suggestions?</p>
  
  <p>This is the code snipet where my number gets displayed:</p>
  
  <pre><code>if (("" + myDouble).length() &gt; 15) {
      screen.setText(String.format("%g", myDouble));
  } else {
      screen.setText("" + myDouble);
  }
  </code></pre>
  
  <p>One problem is that when the <code>else</code> clause is executed, sometimes the numbers get displayed as <code>9.0000E7</code>, which is not favorable and is different from the <code>String.format("%g", myDouble)</code> scientific notation which looks more like <code>9.000e+7</code>.</p>