## scanum checks that number is ok, does not yet recognize enginering format (e.g. 1e7)
from __future__ import print_function
import random
def checkint(i):
s = [n for n in i if n.isdigit()]
return ''.join(s) == i
def scanum(x):
## returns x if it is correct float or integer,
## False otherwise, if you want to raiseValueError comment return False and
## uncomment raise
x=x.lstrip()
if x[0] == '-':
x = x[1:].lstrip('0')
intpart,found,fracpart = x.partition('.')
intpart = intpart or '0' ## use 0.234 instead of .234
ok = checkint(intpart)
if found:
ok = ok and checkint(fracpart)
if not ok:
return False
#raise ValueError,'Improper whole or fraction part'
if found:
return '-' + intpart + '.' + fracpart.rstrip('0')
else: return '-' + intpart
else:
if x[0] == ' + ': x = x[1:]
x = x.lstrip('0')
intpart,found,fracpart = x.partition('.')
intpart = intpart or '0' ## use 0.234 instead of .234
ok = checkint(intpart)
if found:
ok = ok and checkint(fracpart)
if not ok:
return False
##raise ValueError,'Improper whole or fraction part'
if found:
return intpart + '.' + fracpart.rstrip('0')
else: return intpart
## do some random testing
num = 4000
chars = 20
ok = 0
for x in range(num):
i = ''.join([x and i for x in range(1,chars + 1) for i in random.choice('-+1234567890.')])
i = scanum(i)
if i:
print(i)
ok += 1
print()
print( ("Out of %i tested %i long numbers, %i were ok, (%.2f %%)"
% (num, chars, ok, (float(ok)/num*100)) ))