String formatting of floats
<p>I would like to convert a number to a string in such a way that it only shows a certain number of significant digits, without superfluous zeros. The following is an example of some desired in/outputs, given that I want 5 significant digits:</p>

<pre><code>0.0000123456789 &gt; 1.2346e-5
0.00123456789 &gt; 1.2346e-3
0.123456789 &gt; 1.2346e-1
1.23456789 &gt; 1.2346
1234.56789 &gt; 1234.6
1234567.89 &gt; 1.2346e6
</code></pre>

<p>The <code>g</code> option of string formatting (<a href="https://docs.python.org/2/library/string.html#format-specification-mini-language" rel="nofollow">https://docs.python.org/2/library/string.html#format-specification-mini-language</a>) comes pretty close, but its behaviour isn't quite what I'm looking for for numbers smaller than 1, but not <em>much</em> smaller than 1:</p>

<pre><code>"{:.5g}".format(0.000123456789) # returns '0.00012346', I want '1.2346e-4'
</code></pre>

<p>Is it possible to manipulate the behaviour of one of the existing formatters to do this?</p>

<pre><code>if 1 &lt;= x &lt;10000:
    print '{:.5g}'.format(x)

elif 1 &gt; x  or x &gt;= 10000:
    print '{:.4e}'.format(x)
</code></pre>

<p>Similar to A.Kot's answer but not a one liner and outputs what you want given your sample. </p>

python