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:
13.1 -> 13.1
13.1676 -> 13.2
1246 -> 1.25k
560254 -> 560k
6.234e7 -> 62.3M
I have written a function to do this, but it seems overly complicated:
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 >= i_offset + 3:
return '{:{fmt}}'.format(num, fmt=fmt)
for i, sym in enumerate(symbols):
e_thresh = i_offset - 3 * i
if e >= e_thresh:
return '{:{fmt}}{sym}'.format(num/10.**e_thresh, fmt=fmt, sym=sym)
return '{:{fmt}}'.format(num, fmt=fmt)