rust 70 lines · 10 steps

Formatting money with Rust's Display trait

A currency-aware money type stores integer cents and renders them correctly per currency by implementing Display and Debug.

Explained by highlit
1use std::fmt;
2 
3#[derive(Clone, Copy, PartialEq, Eq)]
4pub struct Money {
5 cents: i64,
6 currency: Currency,
7}
8 
9#[derive(Clone, Copy, PartialEq, Eq)]
10pub enum Currency {
11 Usd,
12 Eur,
13 Jpy,
14}
15 
16impl Currency {
17 fn symbol(self) -> &'static str {
18 match self {
19 Currency::Usd => "$",
20 Currency::Eur => "\u{20ac}",
21 Currency::Jpy => "\u{a5}",
22 }
23 }
24 
25 fn decimals(self) -> u32 {
26 match self {
27 Currency::Jpy => 0,
28 _ => 2,
29 }
30 }
31}
32 
33impl fmt::Display for Money {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 let decimals = self.currency.decimals();
36 let sign = if self.cents < 0 { "-" } else { "" };
37 let abs = self.cents.unsigned_abs();
38 
39 if decimals == 0 {
40 return write!(f, "{}{}{}", sign, self.currency.symbol(), abs);
41 }
42 
43 let scale = 10u64.pow(decimals);
44 let whole = abs / scale;
45 let frac = abs % scale;
46 write!(
47 f,
48 "{}{}{}.{:0width$}",
49 sign,
50 self.currency.symbol(),
51 whole,
52 frac,
53 width = decimals as usize,
54 )
55 }
56}
57 
58impl fmt::Debug for Money {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 let code = match self.currency {
61 Currency::Usd => "USD",
62 Currency::Eur => "EUR",
63 Currency::Jpy => "JPY",
64 };
65 f.debug_struct("Money")
66 .field("cents", &self.cents)
67 .field("currency", &code)
68 .finish()
69 }
70}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Storing money as integer cents avoids floating-point rounding errors entirely.
  2. 2Implementing Display lets a type control its own human-readable output through the standard formatting machinery.
  3. 3Currency-specific rules like decimal places belong on the currency itself, keeping formatting logic centralized.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Formatting money with Rust's Display trait — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code