title: Understanding the Python %g in string formatting, achieving Java String.format behavior
body: <p>In Java:</p>
  <pre><code>String test1 = String.format(&quot;%7.2g&quot;, 3e9);
  System.out.println(test1);
  </code></pre>
  <p>This prints <code>3.0e+09</code></p>
  <p>In Python 2.7, if I run this code</p>
  <pre><code>for num in [3e9, 3.1e9, 3.01e9, 3e2, 3.1e2, 3.01e2]:
     print '%7.2g %7.2f %7.2e' % (num, num, num)
  </code></pre>
  <p>I get</p>
  <pre><code>  3e+09 3000000000.00 3.00e+09
  3.1e+09 3100000000.00 3.10e+09
    3e+09 3010000000.00 3.01e+09
    3e+02  300.00 3.00e+02
  3.1e+02  310.00 3.10e+02
    3e+02  301.00 3.01e+02
  </code></pre>
  <p>Huh? It looks like the precision (.2) argument is treated totally differently in Python's <code>%g</code> than in Python's <code>%f</code>, Python's <code>%e</code>, or Java's <code>%g</code>. Here's the <a href="https://docs.python.org/2/library/string.html#format-specification-mini-language" rel="nofollow noreferrer">doc</a> (my emphasis):</p>
  <blockquote>
  <p>General format. For a given precision p &gt;= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.</p>
  <p>The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4 &lt;= exp &lt; p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. <strong>In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.</strong></p>
  <p>Positive and negative infinity, positive and negative zero, and nans, are formatted as inf, -inf, 0, -0 and nan respectively, regardless of the precision.</p>
  <p>A precision of 0 is treated as equivalent to a precision of 1. The default precision is 6.</p>
  </blockquote>
  <p>WTF? Is there any way to prevent those trailing zeros from being removed? The whole point of string formatting is to achieve some consistency, e.g. for text alignment.</p>
  <p>Is there any way to get the Java behavior (essentially the number of significant digits to the right of the decimal point) without having to rewrite the whole thing from scratch?</p>