Luckystrik3
Luckystrik3

Reputation: 93

How to get strings parsed to floats with comma as decimal separator

I am trying to parse a string with the parse() function that is essentially a user input to a f32. There can be floating numbers entered with a comma as a decimal separator - how can I get that parsed as a f32?

So far parsing strings to floats works fine as long as the input is in the format "30" or "30.1" - as soon as the input is "30,1", I get a panic at Result::unwrap(). Is there a way to get parse to accept "," as a decimal separator?

This is my currently used code:

input.trim().parse().unwrap();

I expect parse taking "30" and "30,1" - Best if it would adhere to local decimal conventions

Upvotes: 3

Views: 3334

Answers (2)

Kaplan
Kaplan

Reputation: 3758

When the decimal separator is a comma, the thousands separator is usually a period. Therefore, it should be ensured that the latter isn't present.

let s = "12.345,67"
    .chars()
    .filter(|&c| c != '.' && c != ' ')
    .map(|c| if c == ',' { '.' } else { c })
    .collect::<String>();

Upvotes: 2

evading
evading

Reputation: 3090

Maybe you could just replace the comma with a dot before you pass it to parse.

fn main() {
    let input = "30,6";
    let val: f32 = input.trim().replace(',', ".").parse().unwrap();

    dbg!(val);
}

Works fine for me.

Upvotes: 1

Related Questions