Format Floats With Precision And Signs

Fix decimal places with {:.N}, force signs, zero-pad widths, and switch to scientific notation with {:e} and {:E} format specifiers.

RustData Integrity

Code

rustsnippet
20 lines
fn main() {
    let ratio = 2.0_f64 / 3.0;
    let price = 1234.5_f64;

    // {:.N} 固定 N 位小数(四舍五入,不补零到宽度)
    println!("{:.3}", ratio);
    println!("{:.0}", ratio);

    // + 号强制显式 signs;08.2 用零填充到宽度 8;>10.2 右对齐
    println!("{:+.2}", ratio);
    println!("{:08.2}", price);
    println!("{:>10.2}", price);

    // {:e} 科学计数法;{:E} 用大写 E
    println!("{:e}", 12345.678);
    println!("{:E}", 0.000123);

    // {:?} Debug 格式保留完整精度
    println!("{:?}", ratio);
}

How the snippet works

Format Floats With Precision And Signs reduces to the function main.

ratio is 2.0_f64 / 3.0; {:.3} and {:.0} fix decimal places with rounding, {:+.2} forces an explicit sign, {:08.2} zero-pads to width 8, and {:>10.2} right-aligns within width 10. {:e} and {:E} switch to scientific notation with a lower- or upper-case exponent marker. {:?} prints the Debug form, which keeps f64’s full precision instead of a fixed digit count.

Key statements

let ratio = 2.0_f64 / 3.0;
let price = 1234.5_f64;

Interactive Tools for This Topic

FAQ

How do you run Format Floats With Precision And Signs?
This is a complete program, not a library excerpt — execution starts at the top.