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
|
return re.sub(r'(?<=[,.]) +', r'', val)
|
13
|
|
14
|
def str2int(val): return locale.atoi(clean_numeric(val))
|
15
|
|
16
|
def str2float(val): return locale.atof(clean_numeric(val))
|
17
|
|
18
|
##### Value formatting
|
19
|
|
20
|
def format_str(format, val):
|
21
|
return locale.format_string(format, val, grouping=True)
|
22
|
|
23
|
def int2str(val): return format_str('%d', val)
|
24
|
|
25
|
def float2str(val): return format_str('%f', val)
|
26
|
|
27
|
def to_percent(val, sig_figs=2):
|
28
|
if val >= 1: sig_figs += 1
|
29
|
return format_str('%#.'+str(sig_figs)+'g', val*100)+'%'
|
30
|
|
31
|
def to_si(val, sig_figs=3):
|
32
|
'''Adds SI prefix to value'''
|
33
|
prefix = ''
|
34
|
if val < 1: prefix = 'm'; val *= 1000
|
35
|
return format_str('%#.'+str(sig_figs)+'g', val)+' '+prefix
|