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 |
|
|
'''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 |
989
|
aaronmk
|
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 |
1462
|
aaronmk
|
def float2str(val): return format_str('%f', val)
|
26 |
|
|
|
27 |
989
|
aaronmk
|
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
|