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 std::collections::HashSet; use std::io::{self, BufRead, BufWriter, Write}; fn main() -> io::Result<()> {
Filtering duplicate lines in Rust
stdin
hashset
buffering
Beginner
5 steps
rust
use axum::{extract::{Query, State}, http::StatusCode, Json}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; use serde::{Deserialize, Serialize}; use sqlx::PgPool;
Cursor pagination in an Axum handler
cursor-pagination
keyset-pagination
base64
Advanced
10 steps
rust
use std::num::ParseIntError; fn parse_line(line: &str) -> Result<Vec<i64>, ParseIntError> { line.split(',')
Collecting Results in Rust iterators
iterators
error-handling
result
Intermediate
7 steps
rust
use std::sync::Arc; use axum::{ extract::State,
Offloading work with a channel in Axum
background-jobs
message-passing
shared-state
Intermediate
9 steps
rust
use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Instant; pub struct TimedGuard<'a, T> {
A self-timing mutex guard in Rust
raii
mutex
deref
Advanced
7 steps
rust
use std::error::Error; use std::path::Path; use serde::Deserialize;
Custom CSV deserialization with serde in Rust
serde
csv
deserialization
Intermediate
7 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.