Compute `n * 10^p` as accurately as `f64::from_str` does?

Viewed 173

I've got two values: n: f64 and p: i32, and I need to compute n * 10^p.

I tried two methods:

  1. Using multiplication and f64::powi
  2. Using format!() and f64::from_str

The latter is more accurate (see output below) but obviously inefficient. Is there a way to get the same accuracy without going through a string conversion? Here's my code:

fn main() {
    let f1 = |n: f64, e: i32| n * 10f64.powi(e);
    let f2 = |n: f64, e: i32| format!("{}e{}", n, e).parse::<f64>().unwrap();
    for &n in &[1.1, 2.2, 3.3, 4.4] {
        for &e in &[-2, 2] {
            println!("{} {}", f1(n, e), f2(n, e));
        }
    }
}

Output:

0.011000000000000001 0.011
110.00000000000001 110
0.022000000000000002 0.022
220.00000000000003 220
0.033 0.033
330 330
0.044000000000000004 0.044
440.00000000000006 440

Playground

1 Answers

As always, there is a crate for it: rust_decimal It is not exactly, what you want, but it adds the needed precision to your task without going the way of formatting. Maybe give it a try, it is unfortunately not possible to use it on the playground.

Related