Module 1Getting StartedLesson 2 of 1020 min
Printing & Formatting
Master println!, format!, debug {:?} prints, and numeric formatting you’ll use for prices and rates.
Display vs Debug
{}— human-friendly Display (strings, numbers){:?}— Debug view (great for arrays, structs later){:#?}— pretty Debug
rust
fn main() {
let px = 100.2567;
println!("price = {}", px);
println!("price 2dp = {:.2}", px);
println!("scientific = {:.3e}", 0.000123);
}Output
price = 100.2567
price 2dp = 100.26
scientific = 1.230e-4Named and positional args
rust
fn main() {
println!("{ticker} mid={mid:.4}", ticker = "AAPL", mid = 190.125);
println!("{0} / {1} / {0}", "bid", "ask"); // positional
}Output
AAPL mid=190.1250
bid / ask / bidformat! builds a String
rust
let label = format!("BUY {} @ {:.2}", 100, 150.5);
// label is owned String — useful for logs and order tagsWhy this matters in finance
You’ll constantly print:
- Prices with fixed decimals
- Quantities as integers
- Rates as percents (
0.05→5.0%) - Debug dumps of intermediate Greeks during development
Guided example: order ticket
rust
fn main() {
let side = "BUY";
let qty = 250;
let limit = 412.375;
println!("--- ORDER ---");
println!("side {}", side);
println!("qty {}", qty);
println!("limit {:.3}", limit);
println!("notional {:.2}", qty as f64 * limit);
}Output
--- ORDER ---
side BUY
qty 250
limit 412.375
notional 103093.75Exercise
Format a small mark-to-market blurb with 2 decimal places for money and 1 for percent.
Challenge
Add a third price (yesterday’s close) and print day-change in dollars and percent.
Tips
- {:.2} means 2 digits after the decimal
- as f64 converts integers for multiplication with floats
- format! is like println! but returns a String
Try it live
Printing & FormattingRust 2021
Loading editor…
Output
Press Run to compile and execute.