Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 746
Luckystrik3 Avatar asked Nov 30 '25 16:11

Luckystrik3


1 Answers

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>();
like image 54
Kaplan Avatar answered Dec 02 '25 06:12

Kaplan