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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Storing money as integer cents avoids floating-point rounding errors entirely.
- 2Implementing Display lets a type control its own human-readable output through the standard formatting machinery.
- 3Currency-specific rules like decimal places belong on the currency itself, keeping formatting logic centralized.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/formatting-money-with-rust-s-display-trait-explained-rust-b8f5/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.