Yet another solution, without special functions
(inspired by the answer from @AKX).
def fix_number(n):
return int( n.replace(".","") ) / ( 10 ** ('.' in n) )
for case in ["8.2", "88.2", "888.2", "8.888.2", "8.888.888.2", "8", ""8.888.888"]:
print(case, fix_number(case))
The idea is that '.' in n returns 0 (False) if there are no dots, in which case we divide by 10^0 = 1. It returns 1 (True) if there are one or more dots, in which case we divide by 10.
8.2 8.2
88.2 88.2
888.2 888.2
8.888.2 8888.2
8.888.888.2 8888888.2
8 8.0
8.888.888 888888.8 <- not correct
As you can see, it returns a float even when there are no decimals. Not that the OP asked, but I think that's a nice feature :). However, it fails on the last test-case (which is not among the examples from the OP).
For this case we can replace the function with
def fix_number(n):
return int( n.replace(".","") ) / ( 10 ** ('.' == n[-2]) )
but this fails on 8.
Fixing that leads us to
def fix_number(n):
return int( n.replace(".","") ) / ( 10 ** (n.rfind('.') == max(0,len(n)-2)) )
which outputs
8.2 8.2
88.2 88.2
888.2 888.2
8.888.2 8888.2
8.888.888.2 8888888.2
8 8.0
8.888.888 8888888.0
But at this point is gets a bit ridiculous :). Also the answer by @AKX is about 3.5 times faster.