title: Python floating-point precision format specifier
body: <p>Let's say I have some 32-bit numbers and some 64-bit numbers:</p>
  
  <pre><code>&gt;&gt;&gt; import numpy as np
  &gt;&gt;&gt; w = np.float32(2.4)
  &gt;&gt;&gt; x = np.float32(4.555555555555555)
  &gt;&gt;&gt; y = np.float64(2.4)
  &gt;&gt;&gt; z = np.float64(4.555555555555555)
  </code></pre>
  
  <p>I can print them out with <code>%f</code> but it has extra, unneeded decimals:</p>
  
  <pre><code>&gt;&gt;&gt; '%f %f %f %f' % (w, x, y, z)
  '2.400000 4.555555 2.400000 4.555556'
  </code></pre>
  
  <p>I can use <code>%g</code> but it seems to have a small default precision:</p>
  
  <pre><code>&gt;&gt;&gt; '%g %g %g %g' % (w, x, y, z)
  '2.4 4.55556 2.4 4.55556'
  </code></pre>
  
  <p>I was thinking I should use something like <code>.7</code> for 32-bit values and <code>.15</code> for 64-bit values:</p>
  
  <pre><code>&gt;&gt;&gt; '%.7g %.7g %.15g %.15g' % (w, x, y, z)
  '2.4 4.555555 2.4 4.55555555555556'
  </code></pre>
  
  <p>This seems to work reasonably well, but the precision number is also used up for numbers in front of the decimal place too, e.g. 34567.375768.</p>
  
  <p>In summary, what is the correct way to serialize floating-point values to text such that it preserves appropriate precision for 32-bit and 64-bit values but doesn't use any unnecessary space?</p>
  
  <p><strong>Update</strong>:</p>
  
  <p>Examples of what I <em>think</em> the output should be:</p>
  
  <pre><code>number                float32     float64
  5                     5           5
  0.1                   0.1         0.1
  2.4                   2.4         2.4
  4.555555555555555     4.5555553   4.5555555555555554
  12345678.92345678635  12345679.0  12345678.923456786
  </code></pre>
  
  <p>What I get with .7/.16. This actually looks okay:</p>
  
  <pre><code>&gt;&gt;&gt; v32 = np.array([5, 0.1, 2.4, 4.555555555555555, 12345678.92345678635], dtype=np.float32)
  &gt;&gt;&gt; v64 = np.array([5, 0.1, 2.4, 4.555555555555555, 12345678.92345678635], dtype=np.float64)
  &gt;&gt;&gt; ('%.7g ' * len(v32)) % tuple(v32)
  '5 0.1 2.4 4.555555 1.234568e+07 '
  &gt;&gt;&gt; ('%.16g ' * len(v64)) % tuple(v64)
  '5 0.1 2.4 4.555555555555555 12345678.92345679 '
  </code></pre>