Sub topic 10
Precision, sign, and zero padding
This chapter covers three parts of a format specifier: the precision (.N), the sign flag (+), and the zero flag (0). It assumes you have read the earlier chapters on placeholders, Display, and width, fill, and alignment. You should be comfortable with a spec like {:>8}.
Where these options sit in a specifier
Everything after the colon in a placeholder follows one fixed order. Rust rejects a spec that puts the parts in a different order.
So {:+08.2} reads as: always show a sign, pad with zeros, total width 8, two digits after the decimal point. The sections below cover each option on its own.
Precision
Precision is a dot followed by a number. Its meaning depends on the type being formatted.
| Type | Meaning of `.N` |
|---|---|
| Floating point (`f32`, `f64`) | Exactly N digits after the decimal point |
| Strings (`&str`, `String`) | Keep at most N characters |
| Integers | Ignored |
fn main() {
let pi = 3.14159265_f64;
println!("{:.0}", pi);
println!("{:.2}", pi);
println!("{:.5}", pi);
println!("{:.2}", 2.0_f64);
println!("{:.3}", "abcdef");
println!("{:.2}", 7);
}This prints 3, 3.14, 3.14159, 2.00, abc, and 7. Two details matter here.
- A float is padded with zeros when you ask for more digits than it needs.
2.0with.2becomes2.00. - A string is cut by characters, not bytes. Precision will not split a multi-byte character.
Without precision, {} prints the shortest text that reads back as the same float. That is why println!("{}", 1.0_f64) prints 1, while {:?} prints 1.0.
Rounding follows the stored value
Rust rounds using the exact binary value stored in the float, not the decimal literal you typed. Many decimal fractions cannot be stored exactly, so results can look wrong.
fn main() {
println!("{:.2}", 2.675_f64);
println!("{:.2}", 1.005_f64);
println!("{:.2}", 0.1_f64 + 0.2_f64);
}This prints 2.67, 1.00, and 0.30. The first two values are stored as 2.67499999... and 1.00499999..., so they round down.
Precision in Debug output
{:?} also honors precision for floats, and it passes the setting down into containers.
fn main() {
let v = vec![1.23456_f64, 5.6789];
println!("{:?}", v);
println!("{:.1?}", v);
println!("{:.2?}", Some(3.14159_f64));
}This prints [1.23456, 5.6789], then [1.2, 5.7], then Some(3.14). This is useful when you log a vector of measurements and do not want fifteen digits per value.
Precision from a variable
Precision can also come from a variable or an argument, as the chapter on dynamic width and precision showed. {:.prec$} reads a named value, and {:.*} takes the precision from the argument list just before the value.
The sign flag
By default, Rust prints a minus sign for negative numbers and nothing for positive ones. The + flag forces a sign on every number.
fn main() {
println!("{:+}", 5);
println!("{:+}", -5);
println!("{:+}", 0);
println!("{:+.1}", 2.5_f64);
}This prints +5, -5, +0, and +2.5. The flag applies to integers and floats. There is no flag for a leading space on positive numbers, as C's printf has. Use a width instead if you need columns to line up.
Zero padding
The 0 flag pads a number with leading zeros up to the given width. The zeros go after the sign, not before it.
fn main() {
println!("{:05}", 42);
println!("{:05}", -42);
println!("{:+05}", 42);
println!("{:08.3}", -3.14159_f64);
println!("{:<05}", 42);
println!("{:#06x}", 255);
println!("{:02}:{:02}:{:02}", 7, 5, 9);
}The output is:
00042
-0042
+0042
-003.142
00042
0x00ff
07:05:09Several rules follow from these lines.
- The width counts everything: the sign, the decimal point, and the
0xprefix. In{:05},-42takes 3 characters, so only 2 zeros are added. - The zero flag overrides fill and alignment.
{:<05}still pads on the left, because zeros on the right would change the number's value. - With
#, the prefix comes first and the zeros go between the prefix and the digits.{:#06x}gives0x00ff, which is 6 characters. Remember that you must include the prefix length in the width. - A width smaller than the text never truncates.
{:02}of123prints123.
Combining the options
You can use all three options together. Here is a small ledger that prints amounts held as integer cents.
fn main() {
let rows = [("coffee", 350_i64), ("refund", -1275), ("tip", 5)];
for (name, cents) in rows {
let sign = if cents < 0 { '-' } else { ' ' };
let abs = cents.abs();
println!("{:<8}{}{:>4}.{:02}", name, sign, abs / 100, abs % 100);
}
}The output has one row for each entry:
coffee 3.50
refund - 12.75
tip 0.05The {:02} on the fractional part keeps 5 cents from printing as .5. The sign is added as a separate character so that it stays outside the right-aligned whole-number column. This is also how you avoid float rounding for money.
Honoring these options in your own types
A Display implementation sees the caller's options only if it passes them on. A plain write! ignores precision, sign, and zero padding. The simplest fix is to forward to the inner value's formatter, as in this preview of the chapter on implementing Display.
use std::fmt;
struct Meters(f64);
impl fmt::Display for Meters {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)?;
write!(f, " m")
}
}
fn main() {
println!("{:.1}", Meters(3.14159));
println!("{:+.2}", Meters(2.0));
}This prints 3.1 m and +2.00 m. Passing f to the inner fmt call is what makes the options reach the number.
Common errors
- Expecting precision to round integers. It is ignored for integer types. Convert to a float first, or divide yourself.
- Forgetting that the width includes the sign and prefix. If a hex value looks one digit short, count the
0x. - Writing the parts in the wrong order.
{:.2+}and{:8+}do not compile. Follow the order in the diagram. - Trusting a rounded display. A value that prints as
0.30may still not equal0.3in a comparison.
Exercise
Write a single println! placeholder that prints 7.5_f64 as +0007.50. Then say what {:.1} prints for the string "hello".
Show answer
Use {:+08.2}. The + forces the sign, 0 pads with zeros after the sign, 8 is the total width, and .2 gives two decimals. The text +7.50 is 5 characters, so 3 zeros are added, which gives +0007.50. For the string, precision truncates, so {:.1} prints h.
Exercise
What does println!("{:#06b}", 5) print, and why is the result 6 characters wide?
Show answer
It prints 0b0101. The # flag adds the 0b prefix, which uses 2 of the 6 characters. The zero flag fills the remaining 4 characters with the binary digits of 5 (101) padded with one leading zero.