Sub topic 10
Precision, sign, and zero padding
This chapter assumes you know that a format specifier goes after a colon inside {}, and that width and alignment look like {:>8}. Here you add three more controls: precision, the sign flag, and zero padding.
Precision with `.N`
A dot followed by a number sets the precision. Its meaning depends on the type:
- For floats, it is the number of digits after the decimal point. The value is rounded.
- For strings, it is the maximum number of characters. Longer text is cut.
- For integers, it is ignored.
fn main() {
let x = 3.14159_f64;
println!("[{:.2}]", x);
println!("[{:.0}]", 7.6_f64);
println!("[{:.2}]", 1.0_f64);
println!("[{:.3}]", "abcdef");
println!("[{:.2}]", 5);
}This prints [3.14], [8], [1.00], [abc], and [5]. Precision also pads with zeros, so 1.0 becomes 1.00. That makes it a good fit for prices and measurements.
The sign flag `+`
Rust prints a sign only for negative numbers. Adding + makes it print a sign for positive numbers too.
fn main() {
println!("{:+}", 5);
println!("{:+}", -5);
println!("{:+.1}", 3.14159_f64);
}The output is +5, -5, and +3.1. This helps when you print changes, such as +2.5 or -0.8, and want the columns to line up.
Zero padding with `0`
Put a 0 before the width and the value is padded with zeros instead of spaces. The zeros go after the sign, not before it.
fn main() {
let x = 3.14159_f64;
println!("[{:05}]", 42);
println!("[{:05}]", -42);
println!("[{:+08.2}]", x);
println!("[{:<05}]", 42);
}This prints [00042], [-0042], [+0003.14], and [00042]. The last line shows that the 0 flag overrides alignment. A < has no effect on a zero-padded number, because zeros on the right would change its value.
Reading a full specifier
Specifier parts always appear in the same order: flags, then width, then precision.
| Part | Example | Meaning |
|---|---|---|
| Sign | `+` | Always show the sign |
| Zero | `0` | Pad with zeros after the sign |
| Width | `8` | Minimum total length |
| Precision | `.2` | Digits after the point, or maximum characters |
In {:+08.2}, the width of 8 counts everything: the sign, the digits, and the decimal point. For 3.14159, the text +3.14 is 5 characters, so three zeros are added.
Common mistakes
- Putting precision before width, as in
{:.2 8}. The width comes first. - Forgetting that width includes the sign and the decimal point.
- Using
0with strings. It is accepted but does not pad them with zeros, so use a fill character such as{:*>6}instead.
Exercise
Write a format string that prints -7.456 with a sign, one decimal digit, and zero padding to a total width of 9. What does it print?
Show answer
Use println!("{:+09.1}", -7.456_f64);. It prints -000007.5. The value rounds to -7.5, which is 4 characters, so five zeros are added after the sign to reach width 9.