1 |
989
|
aaronmk
|
# Value to string conversion
|
2 |
|
|
|
3 |
|
|
import locale
|
4 |
|
|
|
5 |
|
|
locale.setlocale(locale.LC_ALL, '') # needed to initialize locale
|
6 |
|
|
|
7 |
|
|
def format_str(format, val):
|
8 |
|
|
return locale.format_string(format, val, grouping=True)
|
9 |
|
|
|
10 |
|
|
def int2str(val): return format_str('%d', val)
|
11 |
|
|
|
12 |
|
|
def to_percent(val, sig_figs=2):
|
13 |
|
|
if val >= 1: sig_figs += 1
|
14 |
|
|
return format_str('%#.'+str(sig_figs)+'g', val*100)+'%'
|
15 |
|
|
|
16 |
|
|
def to_si(val, sig_figs=3):
|
17 |
|
|
'''Adds SI prefix to value'''
|
18 |
|
|
prefix = ''
|
19 |
|
|
if val < 1: prefix = 'm'; val *= 1000
|
20 |
|
|
return format_str('%#.'+str(sig_figs)+'g', val)+' '+prefix
|