Arithmetics with floats and ints

Hey there,
I'm relatively new to the rust ecosystem and have a question about arithmetics with floats and ints:
In my scenario i is my iteration value ranging from 1 to 100 (representing the percentage of the lines I want to use). When I want to calculate the amount of lines with the percentage of i, I can do it this way:
let amount_lines = ((i as f32 / 100.0) * lines.len() as f32) as usize;

I was just wondering if there is some kind of easier way to implement this, without using the explicit typecasts all the time. Thanks already.

Greetings
Xela

You can multiply before dividing:

i * lines.len() / 100

2 Likes

good point, thanks @tuxmain

However doing this you have to be sure that i and lines.len() are small enough, or else the multiplication will overflow.

But in this case it means lines.len() is a lot greater than 100, therefore you can do lines.len() / 100 * i without too much loss of precision.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.