Rust Number Formatting
Number formatting is the shaping of a number inside a format slot. The shaping part comes after a colon in the slot.
Scientific notation
Very large and very small numbers read better with an exponent. e is the lowercase form, E the capital one:
println!("[{:e}] [{:.2e}] [{:E}]", 12345.678, 12345.678, 0.0000123);The same number in other bases
After the colon, b prints binary (base 2). o prints octal (base 8). x or X prints hex (base 16):
println!("bin = {:b}", 255);
println!("oct = {:o}", 255);
println!("hex = {:x}", 255);
println!("HEX = {:X}", 255);Line numbers up in a field
> pushes a value to the right of its field, < to the left, and ^ centres it. A 0 in front pads with zeros, and + always shows the sign:
println!("[{:>5}] [{:<5}] [{:^5}]", 42, 42, 42);
println!("pad = {:05}", 42);
println!("sign = {:+}", 42);Digits after the point
A dot and a count cap the digits after the point, rounding the last one kept:
println!("pi = {:.3}", 3.141592);Exact halves round to even
A value may sit exactly between two choices. Then Rust picks the even one. The rule is the same in every program. It is the same on every machine:
println!("{:.0} {:.0} {:.0}", 2.5, 3.5, -2.5);Example
fn main() {
let n = 255;
println!("dec = {}", n);
println!("bin = {:b}", n);
println!("oct = {:o}", n);
println!("hex = {:x}", n);
println!("HEX = {:X}", n);
println!("right = [{:>5}]", 42);
println!("left = [{:<5}]", 42);
println!("pad = {:05}", 42);
let width = 6;
println!("wide = [{:>width$}]", 42);
println!("pi = {:.3}", 3.141592);
}Key points
- Take the width from a value by ending its name with $: {:>width$} uses the width stored in width
- Precision changes meaning by type: {:.3} is digits after the point for a float, but a cap of 3 characters for text
- Display never switches to e notation by itself: {} prints 1e20 in full, as 100000000000000000000
In this example, one value is printed five ways. The value is 255. First comes plain decimal. Then comes binary 11111111. Then octal 377. Then hex ff and FF. Next, 42 is aligned in a field of width 5. Right-aligned, it gets three spaces before it. Left-aligned, it gets three spaces after it. The square brackets make the padding visible. {:05} pads with zeros instead, giving 00042. The wide line takes its width, 6, from the variable width. Last, {:.3} rounds pi to three digits after the point: 3.142.
Note
The same specs work in every formatting macro — println!, format!, eprintln! and write! all read them the same way.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Which slot prints the number 42 as 00042?