# Value to string conversion

import locale
import re

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

##### String parsing

def str2int_passthru(value):
    try: return int(value)
    except ValueError: return value

def clean_numeric(val):
    '''Removes embedded whitespace, e.g "1, 000".
    Fixes some OCR errors:
        Translates "O" (letter O) to "0" (zero).
    '''
    return re.sub(r'(?<=[,.]) +', r'', val.replace("O", "0"))

def str2int(val): return locale.atoi(clean_numeric(val))

def str2float(val): return locale.atof(clean_numeric(val))

##### Value formatting

def format_str(format, val):
    return locale.format_string(format, val, grouping=True)

def int2str(val): return format_str('%d', val)

def float2str(val): return format_str('%f', val)

def to_percent(val, sig_figs=2):
    if val >= 1: sig_figs += 1
    return format_str('%#.'+str(sig_figs)+'g', val*100)+'%'

def to_si(val, sig_figs=3):
    '''Adds SI prefix to value'''
    prefix = ''
    if val < 1: prefix = 'm'; val *= 1000
    return format_str('%#.'+str(sig_figs)+'g', val)+' '+prefix
