Project

General

Profile

1 1468 aaronmk
# Value to string conversion
2 989 aaronmk
3
import locale
4 1462 aaronmk
import re
5 989 aaronmk
6
locale.setlocale(locale.LC_ALL, '') # needed to initialize locale
7
8 1462 aaronmk
##### String parsing
9
10 3815 aaronmk
def str2int_passthru(value):
11
    try: return int(value)
12
    except ValueError: return value
13
14 1462 aaronmk
def clean_numeric(val):
15 1579 aaronmk
    '''Removes embedded whitespace, e.g "1, 000".
16
    Fixes some OCR errors:
17
        Translates "O" (letter O) to "0" (zero).
18
    '''
19
    return re.sub(r'(?<=[,.]) +', r'', val.replace("O", "0"))
20 1462 aaronmk
21
def str2int(val): return locale.atoi(clean_numeric(val))
22
23
def str2float(val): return locale.atof(clean_numeric(val))
24
25
##### Value formatting
26
27 989 aaronmk
def format_str(format, val):
28
    return locale.format_string(format, val, grouping=True)
29
30
def int2str(val): return format_str('%d', val)
31
32 1462 aaronmk
def float2str(val): return format_str('%f', val)
33
34 989 aaronmk
def to_percent(val, sig_figs=2):
35
    if val >= 1: sig_figs += 1
36
    return format_str('%#.'+str(sig_figs)+'g', val*100)+'%'
37
38
def to_si(val, sig_figs=3):
39
    '''Adds SI prefix to value'''
40
    prefix = ''
41
    if val < 1: prefix = 'm'; val *= 1000
42
    return format_str('%#.'+str(sig_figs)+'g', val)+' '+prefix