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 clean_numeric(val):
11
    '''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

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

    
30
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
(8-8/20)