Skip to content

Instantly share code, notes, and snippets.

@calvingiles
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save calvingiles/9a57267229e5552372cd to your computer and use it in GitHub Desktop.

Select an option

Save calvingiles/9a57267229e5552372cd to your computer and use it in GitHub Desktop.
arbitrary precision number formatter
import math
def num_fmt(num):
i_offset = 24 # change this if you extend the symbols!!!
prec = 3
fmt = '.{p}g'.format(p=prec)
symbols = ['Y', 'Z', 'E', 'P', '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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment