I've got two values: n: f64 and p: i32, and I need to compute n * 10^p.
I tried two methods:
- Using multiplication and
f64::powi - Using
format!()andf64::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