Python string formatting trim float precision to no more than needed
<p>What's the best way to convert a float to a string with no more precision than needed to represent the number, and never more than a specified upper limit precision such that the following would happen?</p>

<pre><code>&gt;&gt;&gt; values = [1, 1., 1.01, 1.00000000001, 1.123456789, 100.123456789]
&gt;&gt;&gt; print([ my_func(value,precision=6) for value in values]) 
['1', '1', '1.01', '1', '1.123457', '100.123457'] 
</code></pre>

<p>I've looked through <code>str.format</code>, but can only find methods for a specific precision that could include too many zeros:</p>

<pre><code>&gt;&gt;&gt; '{:0.6f}'.format(1.0)
'1.000000'
</code></pre>

<p>The <code>g</code> option comes close, but you have to do funny things based on the length of the integer part:</p>

<pre><code>def my_func(value,precision=6):
    return '{v:0.{p}g}'.format(v=value,p=precision+len('{:d}'.format(int(value))))
</code></pre>

<p>Is there a better way?</p>

<p>I don't believe there is a built-in option, but you could just use <code>string.rstrip</code> to remove the trailing zeros from the normal string representation of the float.</p>

<p>EDIT: You would also need to format it to the fixed maximum precision using the %f formatting token before using <code>string.rstrip</code>.</p>

python string string-formatting