Reputation: 1249
Desired result (final values in float):
00 → 0.0
20 → 20.0
15 → 15.0
05 → 0.5
003 → 0.03
01 → 0.1
How would I be supposed to do this? The initial values are a string, but when I convert it to float the zeroes disappear. Are there any pre-made functions for this?
Upvotes: 0
Views: 74
Reputation: 6034
Another simple implementation taking care of exception as well:
import math
x = ['00', '20', '15', '05', '003', '01', '0']
def convert_to_float(val):
try:
if val[0] == '0':
if len(val[1:]) > 0:
decimal_part = float(val[1:])
val = decimal_part / math.pow(10, len(val[1:]))
else:
val = 0.0
else:
val = float(val)
except ValueError:
print('Not a number')
return val
for val in x:
print(convert_to_float(val))
Output:
0.0
20.0
15.0
0.5
0.03
0.1
0.0
Upvotes: 1
Reputation: 4738
I'm not sure what you're trying to do, because you give no specification, only examples. But this works:
for num in ("00", "20", "15", "05", "003", "01"):
if num[0] == '0':
print('0.' + num[1:])
else:
print(num + '.0')
Tested:
$ python3 convert.py
0.0
20.0
15.0
0.5
0.03
0.1
Upvotes: 0
Reputation: 43523
This is easily done with regular expressions.
In [1]: import re
In [2]: def reformat_numbers(num):
...: return float(re.sub('^0', '0.', num))
...:
In [3]: [reformat_numbers(n) for n in ['00', '20', '15', '05', '003', '01']]
Out[6]: [0.0, 20.0, 15.0, 0.5, 0.03, 0.1]
Upvotes: 1
Reputation: 1784
From your examples, it seems like you can just add a decimal after the first char then cast it to float. E.g.
my_num = '002'
my_num = float(my_num[0] + '.' + my_num[1:])
As always when casting, wrap it in a try/except in case the input is not castable.
Upvotes: 0