Last active
August 31, 2016 20:58
-
-
Save natechols/a8ba21ccce756a3d6a0f1e1d67174ebc to your computer and use it in GitHub Desktop.
This file contains 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 re | |
FS_RE = "{([GMkp]{0,1})(:)([\.,]{0,1})([0-9]*)([dfg]{1})}(.*)$" | |
def format_metric(format_str, value): | |
""" | |
Format a report metric (attribute or table column value) according to our | |
in-house rules. These resemble Python format strings (plus optional | |
suffix), but with the addition of optional scaling flags. | |
""" | |
if value is None: | |
return "NA" | |
elif format_str is None: | |
return str(value) | |
else: | |
m = re.match(FS_RE, format_str) | |
if m is None: | |
raise ValueError("Format string '{s}' is uninterpretable".format( | |
s=format_str)) | |
if m.groups()[0] == 'p': | |
value *= 100.0 | |
elif m.groups()[0] == 'G': | |
value /= 1000000000.0 | |
elif m.groups()[0] == 'M': | |
value /= 1000000.0 | |
elif m.groups()[0] == 'k': | |
value /= 1000.0 | |
if isinstance(value, float) and m.groups()[4] == 'd': | |
value = int(value) | |
fs_python = "{{:{:s}{:s}{:s}}}".format(*(m.groups()[2:5])) | |
formatted = fs_python.format(value) | |
# the percent symbol can be implicit | |
if m.groups()[0] == 'p' and m.groups()[-1] == '': | |
return formatted + "%" | |
else: | |
return formatted + m.groups()[-1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment