I currently need to compute the result of a given integer divided by another integer, and get the result as a floating-point number.
I can guarantee the result is going be less than 2^24 + 1 (which is the maximum representable integer number without loss in IEEE 754) but the dividend and/or the dividor may exceed that value (and be up to usize::MAX each).
I need perfect integer precision. So I can't convert both integers to a f64 before dividing them.
So concretely I have to compute a / b where a: usize, b: usize and the result is in the [0, 2^24].
I then need to print this result with a precision if N decimals (up to 3). How can I do this?
fn print_with_3_digits(a: usize, b: usize) {
let a_mul = (a as u128) * 1000;
let b = b as u128;
let div = a_mul / b;
let frac = div % 1000;
let rest = div / 1000;
println!("{}.{:#03}", rest, frac);
}
That's exactly what I needed, I just didn't think about converting a higher integer representation and also didn't know you could get the nth first digits of a number.
Here is my final solution, generating a string for any set of (divident, dividor, precision) - type changed from usize to u64 in the meantime but it works with smaller number types as well.
Note that it could very probably be optimized, I just don't know how, and it works fine enough for me
Why do you do the division a second time to find the rounding decimal place? Just do it once with the higher precision an change the rest of the code to take that into account.
Note that .to_string() works on anything that's impl Display, so I think @H2CO3's suggestion here is to write it via Display so that you can approx_int_div(…).to_string() in places that actually need the string, but still efficiently include it in other places -- like println! -- without being forced to have the intermediate String.
Also, even if you do want a String as the final result, the .push_str(&format!(…)) is still unconditionally an unnecessary allocation, as it's a temporary.