Format precision in Rust
Precision is written after a dot inside the format specification, but its meaning depends on the type being formatted. The same .2 is not a universal “two characters” instruction.
assert_eq!(format!("{:.2}", 3.14159), "3.14");
assert_eq!(format!("{:.4}", "rustacean"), "rust");
assert_eq!(format!("{:.2e}", 1234.567), "1.23e3");Floating-point values
Section titled “Floating-point values”For floating-point formatting, precision controls the number of digits after the decimal point. "{:.2}" formats 3.14159 as 3.14.
The rule also applies to scientific notation. "{:.2e}" keeps two digits after the decimal point in the mantissa.
Strings and other non-numeric output
Section titled “Strings and other non-numeric output”For non-numeric formatting, precision behaves like a maximum width. If the formatted result is longer, Rust truncates it before applying any requested width and alignment.
That makes precision useful when a text field must not exceed a certain displayed length. It is different from width: width pads short output, while precision can limit long output.
Integral values
Section titled “Integral values”Precision is ignored for integral formatting. If you need a minimum number of visible positions for an integer, use width and zero padding instead:
{:05}That is a width of five with sign-aware zero padding, not a precision of five.
Dynamic precision
Section titled “Dynamic precision”Precision can also come from another usize formatting argument instead of being written directly into the format string. Rust supports named and positional parameter forms, plus a special asterisk form documented by std::fmt.
Keep that mechanism separate from the meaning of precision itself: the parameter chooses the number, while the formatted type decides what that number means. See arguments and captured variables for the broader argument-selection model.