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
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With