How does one round a floating point number to a specified number of digits?

前端 未结 2 1084
忘掉有多难
忘掉有多难 2020-12-10 10:31

How does one round a f64 floating point number in Rust to a specified number of digits?

2条回答
  •  春和景丽
    2020-12-10 10:54

    To add to @huon's great answer, if you want to round a floating point number for display purposes, but you don't know the precision at compile time, you can use the precision formatting syntax as follows:

    fn main() {
        let precision = 3;
        let x = 12.34567;
        println!("{:.1$}", x, precision); // prints 12.346 and works with `format!` as well
    }
    

    The documentation of std::fmt has more examples on the syntax.

提交回复
热议问题