Last active
August 29, 2015 14:01
-
-
Save calvingiles/9a57267229e5552372cd to your computer and use it in GitHub Desktop.
arbitrary precision number formatter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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