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,844 questions

51,765 answers

573 users

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

1 Answer

0 votes
fn to_float(input: &str) -> f64 {
    let comma_count = input.matches(',').count();
    let dot_count = input.matches('.').count();

    let last_comma = input.rfind(',');
    let last_dot = input.rfind('.');

    let mut s = input.to_string();

    if comma_count > 0 && dot_count > 0 {
        if last_comma > last_dot {
            s = s.replace('.', "");
            s = s.replace(',', ".");
        } else {
            s = s.replace(',', "");
        }
    } else if comma_count > 0 {
        s = s.replace('.', "");
        s = s.replace(',', ".");
    } else {
        s = s.replace(',', "");
    }

    s.parse::<f64>().unwrap_or_else(|_| {
        panic!("Invalid number format: '{}'", input)
    })
}

fn main() {
    println!("{:.3}", to_float("1,224,533.533"));
    println!("{:.3}", to_float("1.224.533,533"));
    println!("{:.2}", to_float("2.354,67"));
    println!("{:.2}", to_float("2,354.67"));
}

 
 
/*
run:
   
1224533.533
1224533.533
2354.67
2354.67
   
*/
 


answered Jun 27, 2025 by avibootz
...