title: How do I format a number in python with k for thousand etc for arbitrary preffix symbols?
body: <p>I wish to format numbers when passing to a plot annotation so they are 'pretty printed' with "k" for thousand, etc. and precision rounding, for example for 3 digit precision:</p>
  
  <pre><code>13.1    -&gt; 13.1
  13.1676 -&gt; 13.2
  1246    -&gt; 1.25k
  560254  -&gt; 560k
  6.234e7 -&gt; 62.3M
  </code></pre>
  
  <p>I have written a function to do this, but it seems overly complicated:</p>
  
  <pre><code>import math
  
  
  def num_fmt(num):
      i_offset = 15 # change this if you extend the symbols!!!
      prec = 3
      fmt = '.{p}g'.format(p=prec)
      symbols = ['Y', 'T', 'G', 'M', 'k', '', 'm', 'u', 'n']
  
      e = math.log10(abs(num))
      if e &gt;= i_offset + 3:
          return '{:{fmt}}'.format(num, fmt=fmt)
      for i, sym in enumerate(symbols):
          e_thresh = i_offset - 3 * i
          if e &gt;= e_thresh:
              return '{:{fmt}}{sym}'.format(num/10.**e_thresh, fmt=fmt, sym=sym)
      return '{:{fmt}}'.format(num, fmt=fmt)
  </code></pre>