How do I print a Rust floating-point number with all available precision?

后端 未结 4 2041
长情又很酷
长情又很酷 2021-01-17 17:47

I am implementing the CORDIC algorithm for the sin trigonometric function. In order to do this, I need to hardcode/calculate a bunch of arctangent values. Right

4条回答
  •  没有蜡笔的小新
    2021-01-17 18:18

    Using the precision format specifier is the correct answer, but to print all available precision, simply refrain from specifying the number of digits to display:

    // prints 1
    println!("{:.}", 1_f64);
    
    // prints 0.000000000000000000000000123
    println!("{:.}", 0.000000000000000000000000123_f64); 
    

    This way, you will not truncate values nor will you have to trim excess zeros, and the display will be correct for all values, regardless of whether they are very large or very small.

    Playground example

    For completeness, the precision format specifier also supports a specifying a fixed precision (as per the accepted answer):

    // prints 1.0000
    println!("{:.4}", 1_f64);
    

    as well as a precision specified at runtime (does not need to be const, of course):

    // prints 1.00
    const PRECISION: usize = 2;
    println!("{:.*}", PRECISION, 1_f64); // precision specifier immediately precedes positional argument
    

提交回复
热议问题