Project

General

Profile

1
# Value to string conversion
2

    
3
import locale
4
import re
5

    
6
locale.setlocale(locale.LC_ALL, '') # needed to initialize locale
7

    
8
##### String parsing
9

    
10
def str2int_passthru(value):
11
    try: return int(value)
12
    except ValueError: return value
13

    
14
def clean_numeric(val):
15
    '''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

    
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
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
def float2str(val): return format_str('%f', val)
33

    
34
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
(17-17/50)