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
def clean_numeric(val):
11 1579 aaronmk
    '''Removes embedded whitespace, e.g "1, 000".
12
    Fixes some OCR errors:
13
        Translates "O" (letter O) to "0" (zero).
14
    '''
15
    return re.sub(r'(?<=[,.]) +', r'', val.replace("O", "0"))
16 1462 aaronmk
17
def str2int(val): return locale.atoi(clean_numeric(val))
18
19
def str2float(val): return locale.atof(clean_numeric(val))
20
21
##### Value formatting
22
23 989 aaronmk
def format_str(format, val):
24
    return locale.format_string(format, val, grouping=True)
25
26
def int2str(val): return format_str('%d', val)
27
28 1462 aaronmk
def float2str(val): return format_str('%f', val)
29
30 989 aaronmk
def to_percent(val, sig_figs=2):
31
    if val >= 1: sig_figs += 1
32
    return format_str('%#.'+str(sig_figs)+'g', val*100)+'%'
33
34
def to_si(val, sig_figs=3):
35
    '''Adds SI prefix to value'''
36
    prefix = ''
37
    if val < 1: prefix = 'm'; val *= 1000
38
    return format_str('%#.'+str(sig_figs)+'g', val)+' '+prefix