Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to convert a string with either, or . as decimal/thousand separators into a float in Python

2 Answers

0 votes
def to_float(input_str: str) -> float:
    comma_count = input_str.count(',')
    dot_count = input_str.count('.')

    last_comma = input_str.rfind(',')
    last_dot = input_str.rfind('.')

    str_copy = input_str

    if comma_count > 0 and dot_count > 0:
        if last_comma > last_dot:
            str_copy = str_copy.replace('.', '')
            str_copy = str_copy.replace(',', '.')
        else:
            str_copy = str_copy.replace(',', '')
    elif comma_count > 0:
        str_copy = str_copy.replace('.', '')
        str_copy = str_copy.replace(',', '.')
    else:
        str_copy = str_copy.replace(',', '')

    return float(str_copy)


print(f"{to_float('1,224,533.533'):.3f}")
print(f"{to_float('1.224.533,533'):.3f}")
print(f"{to_float('2.354,67'):.2f}")
print(f"{to_float('2,354.67'):.2f}")



'''
run

1224533.533
1224533.533
2354.67
2354.67

'''

 



answered Jun 27, 2025 by avibootz
0 votes
def convert_to_float(s):
    # Replace thousand separator (comma) and adjust decimal separator
    s = s.replace(",", "").replace(".", ".")
    return float(s)

string = "1,224,533.533"  
number = convert_to_float(string)
print(number)  


string = "1.224,533,533"  
number = convert_to_float(string) 
print(number)  

'''
string = "1.224.533,533"  
# ValueError: could not convert string to float: '1.224.533533'
number = convert_to_float(string) 
print(number)  
'''

string = "2.354,67"  
number = convert_to_float(string)
print(number)  

string = "2,354.67"  
number = convert_to_float(string)
print(number)  



'''
run

1224533.533
1224533.533
2354.67
2354.67

'''

 



answered Jun 27, 2025 by avibootz
...