read number containing multiple decimal points

Viewed 81

how can I convert the following strings to float numbers (they are written to represent numbers but sadly "," was replaced a ".") anyway, the last point is only the decimal point

8.500.00
900.03
1.000.000.67

I am looking to create a function to return them back as float numbers, output is as this

8500.00
900.03
1000000.6

I tried regex to solve such as '\d+\.*[\.\d+]$', I am not sure if regex is the best way

Any help is appreciated

7 Answers

Solution using re module (regex101):

s = '''
8.500.00
900.03
1.000.000.67
9,555.2
'''

import re

print( re.sub(r'(\.|,)(?=.*?\.\d+)', '', s) )

Prints:

8500.00
900.03
1000000.67
9555.2

This solution uses str.count and str.replace.

n = """\
8.500.00
900.03
1.000.000.67
100.02
200""".splitlines()

for number in n:
    dot = number.count('.')
    number = number.replace('.', '', dot-1)
    print(number)

Prints:

8500.00
900.03
1000000.67
100.02
200

you can do with split and join if you don't like re.

s = "11.220.33"
list_s = s.split(".")
new_s= "".join(list_s[:-1])+"."+list_s[-1]
print(new_s)

Since we know the only actual decimal point is the last one in the number, perhaps we can use reverse iteration to eliminate all decimal points before it. It might be possible to do this with regex, but that might be more trouble than it's worth.

Some pseudocode I'm thinking of that might get the job done:

found_dot = False

for c in reversed(num):
    if not found_dot and c == '.':
        found_dot = True
    else:
        remove dot from string

return float(num)

That should remove all decimal points except the last one, resulting in a nice string that can be converted to float.

I haven't tested this myself, so please let me know if you encounter more errors or if you have more questions.

See this let a = "8.500.00"

a=a.split('.')
a=float("".join(a))
a=(a/10**(x))

where x is number of digits after decimal point which can be easily calculated by applying reverse loop and get index of first '.'

def convert_str_num(str_num):
    str_num_lst = str_num.split(".")
    int_part, decimal_part = "".join(str_num_lst[:-1]), str_num_lst[-1]
    return float(f"{int_part}.{decimal_part}")

Here is a simple, decidedly unpythonic way to fix it:

def dot_fixer(n):   
    fixed = ""
    last_dot = n.rfind(".")

    for i in range(0, len(num)):
        if num[i] == '.' and i < last_dot:
            continue
        else:
            fixed += num[i]

    return float(fixed)

num = "8.500.00"
print(dot_fixer(num))
Related