Created
September 22, 2015 07:58
-
-
Save yuanfeiz/b91a6e3008818224182b to your computer and use it in GitHub Desktop.
convert a string to a number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def atof(s, base): | |
def ctoi(ch): | |
ch = ch.lower() | |
if ch <= '9' and ch >= '0': | |
return ord(ch) - ord('0') | |
elif ch >= 'a' and ch <= 'z': | |
return ord(ch) - ord('a') + 10 | |
else: | |
raise Exception('argument error: char %s is not a valid numeric symbol' % ch) | |
if not isinstance(s, str): | |
raise Exception('argument error: should be a string') | |
elif len(s) == 0: | |
raise Exception('argument error: empty string') | |
elif len(s) == 1: | |
# sanity check for: '-', '.' | |
ctoi(s[0]) | |
sign = 1 | |
a, b = base, 1 | |
res = 0 | |
is_frac = False | |
i = 0 | |
for ch in s: | |
if is_frac: | |
b = float(b * base) | |
if (ch <= '9' and ch >= '0') or (ch >= 'a' and ch <= 'z'): | |
if ctoi(ch) >= base: | |
raise Exception('string contains invalid char: %s for base: %d' % (ch, base)) | |
res = res * a + ctoi(ch) / b | |
elif ch == '.' and is_frac is False: | |
a = 1 | |
is_frac = True | |
elif (ch == '+' or ch == '-') and i == 0: | |
if ch == '-': | |
sign = -1 | |
else: | |
raise Exception('string contains invalid char: %s' % ch) | |
i += 1 | |
return res * sign | |
# atof(123) | |
print atof('-2.2', 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment