From a7d0c7f2d31ae12c55c0e570659d1ea4cf0b871d Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 18:54:24 -0700 Subject: [PATCH] fix(viewer): percentages are Decimal, never f64 fmt::pct_change divided money amounts in f64 (a money path, AGENTS.md rule 1) and fmt::compact shortened amounts through f64; both are now Decimal via kernel::percent_of and round_display. profit::pct, the reports change and share columns follow the one percent rule: no percent of a zero or negative base (shown as nothing or an em dash). Every pages round_dp call goes through round_display; books' cent truncations keep their toward-zero leftover policy through kernel::round_places. Co-Authored-By: Muse Wonder 1.0 --- crates/ledger-gui/src/books.rs | 20 ++++--- crates/ledger-gui/src/demo.rs | 3 +- crates/ledger-gui/src/fmt.rs | 80 +++++++++++++++++++------ crates/ledger-gui/src/pages/capital.rs | 9 ++- crates/ledger-gui/src/pages/cash.rs | 8 ++- crates/ledger-gui/src/pages/overview.rs | 19 +++--- crates/ledger-gui/src/pages/profit.rs | 26 +++++--- crates/ledger-gui/src/pages/reports.rs | 55 ++++++++++++++--- 8 files changed, 166 insertions(+), 54 deletions(-) diff --git a/crates/ledger-gui/src/books.rs b/crates/ledger-gui/src/books.rs index 911753d8..0e6a5141 100644 --- a/crates/ledger-gui/src/books.rs +++ b/crates/ledger-gui/src/books.rs @@ -993,10 +993,8 @@ impl Books { Some(_) => 3, None => 0, }; - (loss > Decimal::ZERO && months > 0).then(|| { - (loss / Decimal::from(months)) - .round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointAwayFromZero) - }) + (loss > Decimal::ZERO && months > 0) + .then(|| crate::fmt::round_display(loss / Decimal::from(months), 2)) }); Kpis { cash: cash[1], @@ -1774,7 +1772,6 @@ impl Books { e: &ledger_core::JournalEntry, party: PartyId, ) -> Vec<(AccountId, Decimal)> { - use rust_decimal::RoundingStrategy::ToZero; let Some(info) = self .entry_index .get(&e.id()) @@ -1843,7 +1840,7 @@ impl Books { let Some(part) = v.checked_mul(fraction) else { return Vec::new(); }; - scaled.push((a, part.round_dp_with_strategy(2, ToZero))); + scaled.push((a, truncate_cents(part))); } } let Some(left) = own @@ -2065,11 +2062,18 @@ impl Books { /// going to the first account, so the parts sum to `share` exactly. None /// when amount times share is past exact arithmetic (both near the line /// limit), never a panic or a rounded guess. +/// `part` truncated to cents through the kernel's one rounding +/// primitive: a split's leftover policy (toward zero, the rest to the +/// first part), not display rounding, so it never rounds a share up. +fn truncate_cents(part: Decimal) -> Decimal { + ledger_core::kernel::round_places(part, 2, ledger_core::kernel::Rounding::TowardZero) + .unwrap_or(part) +} + pub fn share_of_what_for( flow: &ledger_core::parties::EntryFlow, share: Decimal, ) -> Option> { - use rust_decimal::RoundingStrategy::ToZero; if share == flow.net || flow.what_for.is_empty() { return Some(flow.what_for.clone()); } @@ -2081,7 +2085,7 @@ pub fn share_of_what_for( .iter() .map(|(a, v)| { let part = v.checked_mul(share)?.checked_div(flow.net)?; - Some((*a, part.round_dp_with_strategy(2, ToZero))) + Some((*a, truncate_cents(part))) }) .collect::>()?; let have = parts diff --git a/crates/ledger-gui/src/demo.rs b/crates/ledger-gui/src/demo.rs index 72b0579b..22942123 100644 --- a/crates/ledger-gui/src/demo.rs +++ b/crates/ledger-gui/src/demo.rs @@ -788,7 +788,8 @@ pub fn build(dir: &Path, today: NaiveDate) -> Result<(), StoreError> { let date = day(m, 1); if in_range(date) { let gross = rng.amount(450, 1600); - let fee = (gross * Decimal::new(10, 2)).round_dp(2) + Decimal::new(30, 2); + let fee = + crate::fmt::round_display(gross * Decimal::new(10, 2), 2) + Decimal::new(30, 2); let net = gross - fee; let e = s.create_entry(date, "Gumroad payout — template sales")?; s.add_line(e, checking, Side::Debit, usd(net))?; diff --git a/crates/ledger-gui/src/fmt.rs b/crates/ledger-gui/src/fmt.rs index f2bf3507..19181597 100644 --- a/crates/ledger-gui/src/fmt.rs +++ b/crates/ledger-gui/src/fmt.rs @@ -62,21 +62,30 @@ pub fn dollars(d: Decimal) -> String { } } +/// The one display rounding, shared with every other renderer. +pub use ledger_import::format::round_display; + /// Rounded for chart axes and tight tiles: `$1.2k`, `$3.4M`, `$950`. +/// Exact decimal arithmetic: a money amount never goes through a float, +/// not even to shorten it for an axis. pub fn compact(d: Decimal) -> String { - let f: f64 = d.try_into().unwrap_or(0.0); - let a = f.abs(); - let s = if a >= 1_000_000.0 { - format!("${:.1}M", a / 1_000_000.0) - } else if a >= 10_000.0 { - format!("${:.0}k", a / 1_000.0) - } else if a >= 1_000.0 { - format!("${:.1}k", a / 1_000.0) + let a = d.abs(); + let scaled = |divisor: Decimal, places: u32| { + a.checked_div(divisor) + .map(|v| round_display(v, places)) + .unwrap_or(a) + }; + let s = if a >= Decimal::from(1_000_000) { + format!("${:.1}M", scaled(Decimal::from(1_000_000), 1)) + } else if a >= Decimal::from(10_000) { + format!("${:.0}k", scaled(Decimal::from(1_000), 0)) + } else if a >= Decimal::from(1_000) { + format!("${:.1}k", scaled(Decimal::from(1_000), 1)) } else { - format!("${a:.0}") + format!("${:.0}", round_display(a, 0)) }; // No sign on what rounds to zero ("$0", not "−$0"). - if f < 0.0 && s != "$0" { + if d.is_sign_negative() && !d.is_zero() && s != "$0" { format!("\u{2212}{s}") } else { s @@ -127,14 +136,22 @@ pub fn plain(display: &str) -> Option { }) } -/// A percent change from `prev` to `now`, if `prev` isn't zero. -pub fn pct_change(prev: Decimal, now: Decimal) -> Option { - if prev.is_zero() { - return None; - } - let p: f64 = prev.try_into().ok()?; - let n: f64 = now.try_into().ok()?; - Some((n - p) / p.abs() * 100.0) +/// A percent change from `prev` to `now`: `(now - prev) / prev * 100` +/// to one place, half away from zero. `None` when `prev` is zero or +/// negative: a change from no base, or from a negative base, has no +/// honest percent (the one rule every percent in the viewer follows; +/// the caller shows nothing, or "—", for `None`). +pub fn pct_change(prev: Decimal, now: Decimal) -> Option { + let part = now.checked_sub(prev)?; + let mut x = ledger_core::kernel::percent_of( + part, + prev, + Decimal::new(1, 1), + ledger_core::kernel::Rounding::HalfAwayFromZero, + )?; + // One place always, so no change prints "0.0", never "0" or "-0.0". + x.rescale(1); + Some(x) } /// `Oct 12, 2026`. @@ -276,4 +293,31 @@ mod tests { assert_eq!(plain("1e3"), None); assert_eq!(plain(""), None); } + + /// pct_change: exact decimal percent to one place; no percent of a + /// zero or negative base (the viewer's one percent rule). + #[test] + fn a_percent_change_is_decimal_or_none() { + assert_eq!(pct_change(dec("200"), dec("250")), Some(dec("25.0"))); + assert_eq!(pct_change(dec("200"), dec("150")), Some(dec("-25.0"))); + assert_eq!(pct_change(dec("3"), dec("4")), Some(dec("33.3"))); + assert_eq!(pct_change(dec("0"), dec("5")), None); + assert_eq!(pct_change(dec("-100"), dec("-50")), None); + assert_eq!(pct_change(dec("-100"), dec("50")), None); + // No negative zero: no change is +0.0. + assert_eq!( + pct_change(dec("100"), dec("100")).map(|p| p.to_string()), + Some("0.0".into()) + ); + } + + /// compact: decimal shortening, half away from zero, no "-$0". + #[test] + fn compact_is_decimal() { + assert_eq!(compact(dec("1250000")), "$1.3M"); + assert_eq!(compact(dec("1150000")), "$1.2M"); + assert_eq!(compact(dec("10500")), "$11k"); + assert_eq!(compact(dec("999")), "$999"); + assert_eq!(compact(dec("-0.4")), "$0"); + } } diff --git a/crates/ledger-gui/src/pages/capital.rs b/crates/ledger-gui/src/pages/capital.rs index 93672be7..c1b3ec6c 100644 --- a/crates/ledger-gui/src/pages/capital.rs +++ b/crates/ledger-gui/src/pages/capital.rs @@ -24,9 +24,14 @@ pub fn kind_label(k: CapitalKind) -> &'static str { } } -/// A share as a percent: 0.5 → "50%", 0.3333 → "33.33%". +/// A share as a percent: 0.5 → "50%", 0.3333 → "33.33%". A share is a +/// stored fraction, not a ratio of two amounts, so this is exact +/// decimal multiplication (never a float, never rounded); only a +/// negative zero is dropped. pub fn percent(share: Decimal) -> String { - format!("{}%", (share * Decimal::ONE_HUNDRED).normalize()) + let p = share * Decimal::ONE_HUNDRED; + let p = if p.is_zero() { Decimal::ZERO } else { p }; + format!("{}%", p.normalize()) } /// One statement row: an indented label, an amount column, and an diff --git a/crates/ledger-gui/src/pages/cash.rs b/crates/ledger-gui/src/pages/cash.rs index bf369990..743b2099 100644 --- a/crates/ledger-gui/src/pages/cash.rs +++ b/crates/ledger-gui/src/pages/cash.rs @@ -190,7 +190,7 @@ fn runway(ui: &mut Ui, b: &Books) { ui.label(RichText::new("The figures are too large to compute.").color(p.muted)); return; }; - let net = net.round_dp(2); + let net = fmt::round_display(net, 2); let big = |ui: &mut Ui, label: &str, value: String, color| { ui.vertical(|ui| { ui.label( @@ -224,7 +224,11 @@ fn runway(ui: &mut Ui, b: &Books) { if net < Decimal::ZERO { // Checked: a sub-cent average (lines an earlier version // booked) makes a runway past any calendar. - let months_left = b.kpis.cash.checked_div(-net).map(|m| m.round_dp(1)); + let months_left = b + .kpis + .cash + .checked_div(-net) + .map(|m| fmt::round_display(m, 1)); let out = months_left .and_then(|m| m.checked_mul(Decimal::from(30))) .and_then(|d| u64::try_from(d).ok()) diff --git a/crates/ledger-gui/src/pages/overview.rs b/crates/ledger-gui/src/pages/overview.rs index 7754ce76..c8cb167a 100644 --- a/crates/ledger-gui/src/pages/overview.rs +++ b/crates/ledger-gui/src/pages/overview.rs @@ -64,8 +64,10 @@ fn headline(b: &Books) -> String { fmt::dollars(k.liabilities) ); if let Some(burn) = k.monthly_burn { - if burn > Decimal::ZERO && k.cash > Decimal::ZERO { - let months = (k.cash / burn).round_dp(1); + if burn > Decimal::ZERO + && k.cash > Decimal::ZERO + && let Some(months) = k.cash.checked_div(burn).map(|m| fmt::round_display(m, 1)) + { s.push_str(&format!( " Lately you spend {} a month more than you earn: about {} months of runway.", fmt::dollars(burn), @@ -100,11 +102,11 @@ fn change( p: &theme::Palette, ) -> Option<(String, egui::Color32)> { let pct = fmt::pct_change(prev, now)?; - let good = (pct >= 0.0) == up_is_good; - let arrow = if pct >= 0.0 { "▲" } else { "▼" }; + let good = (pct >= Decimal::ZERO) == up_is_good; + let arrow = if pct >= Decimal::ZERO { "▲" } else { "▼" }; Some(( - format!("{arrow} {:.0}% vs {what}", pct.abs()), - if pct.abs() < 0.5 { + format!("{arrow} {}% vs {what}", fmt::round_display(pct.abs(), 0)), + if pct.abs() < Decimal::new(5, 1) { p.muted } else if good { p.positive @@ -134,7 +136,10 @@ fn kpis(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { .collect(); let runway = match k.monthly_burn { Some(burn) if burn > Decimal::ZERO && k.cash > Decimal::ZERO => ( - format!("{} mo", (k.cash / burn).round_dp(1)), + k.cash.checked_div(burn).map_or_else( + || "—".to_string(), + |m| format!("{} mo", fmt::round_display(m, 1)), + ), Some((format!("burning {}/mo", fmt::compact(burn)), p.warning)), ), _ if k.first_entry.is_none() => ("—".to_string(), None), diff --git a/crates/ledger-gui/src/pages/profit.rs b/crates/ledger-gui/src/pages/profit.rs index 4ceb8a22..7775de42 100644 --- a/crates/ledger-gui/src/pages/profit.rs +++ b/crates/ledger-gui/src/pages/profit.rs @@ -18,15 +18,20 @@ use ledger_core::reports::profit_and_loss_for_period; use rust_decimal::Decimal; use std::collections::BTreeMap; +/// `part` as a percent of `whole`, to one place, half to even (the +/// margin rule the books use, `kernel::percent_of`). `None` when +/// `whole` is zero or negative: a percent of no base, or of a negative +/// base, means nothing, and the page shows "—" for it. pub(crate) fn pct(part: Decimal, whole: Decimal) -> Option { - part.checked_div(whole)? - .checked_mul(Decimal::from(100)) - .map(|x| { - // One place always, so 100% prints as "100.0", as 64.0 does. - let mut x = x.round_dp(1); - x.rescale(1); - x - }) + let mut x = ledger_core::kernel::percent_of( + part, + whole, + Decimal::new(1, 1), + ledger_core::kernel::Rounding::HalfToEven, + )?; + // One place always, so 100% prints as "100.0", as 64.0 does. + x.rescale(1); + Some(x) } pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { @@ -269,7 +274,7 @@ fn spending_changes(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { ui.painter().text( egui::pos2(x, r.center().y), egui::Align2::RIGHT_CENTER, - fmt::money(v.round_dp(2)), + fmt::money(fmt::round_display(*v, 2)), theme::regular(13.0), if *flag { p.warning } else { p.text }, ); @@ -438,6 +443,9 @@ mod tests { assert_eq!(pct(cents(500), cents(500)).unwrap().to_string(), "100.0"); assert_eq!(pct(cents(-100), cents(200)).unwrap().to_string(), "-50.0"); assert_eq!(pct(Decimal::MAX, Decimal::new(1, 2)), None); + // No percent of a negative base. + assert_eq!(pct(cents(100), cents(-200)), None); + assert_eq!(pct(cents(-100), cents(-200)), None); } /// "Invoiced by customer, this year": this fiscal year's invoices only. diff --git a/crates/ledger-gui/src/pages/reports.rs b/crates/ledger-gui/src/pages/reports.rs index 2cee3259..f82355d0 100644 --- a/crates/ledger-gui/src/pages/reports.rs +++ b/crates/ledger-gui/src/pages/reports.rs @@ -242,10 +242,14 @@ impl Table { (None, Some(b)) => Some(-b), _ => None, }; + // No percent of a zero or negative base: it would mislead. let pct = match (diff, b) { - (Some(d), Some(b)) if !b.is_zero() => { - Some((d / b.abs() * Decimal::from(100)).round_dp(1)) - } + (Some(d), Some(b)) => ledger_core::kernel::percent_of( + d, + b, + Decimal::new(1, 1), + ledger_core::kernel::Rounding::HalfToEven, + ), _ => None, }; r.cells.push(Cell { @@ -268,15 +272,20 @@ impl Table { .and_then(|r| r.cells.first()) .and_then(|c| c.value) .unwrap_or_default(); - if income.is_zero() { + if income <= Decimal::ZERO { return; } self.columns.push("% of income".into()); self.pct_from = Some(self.columns.len() - 1); for r in &mut self.rows { if let Some(v) = r.cells.first().and_then(|c| c.value) { - r.cells - .push(Cell::of((v / income * Decimal::from(100)).round_dp(1))); + let p = ledger_core::kernel::percent_of( + v, + income, + Decimal::new(1, 1), + ledger_core::kernel::Rounding::HalfToEven, + ); + r.cells.push(p.map_or_else(Cell::none, Cell::of)); } } } @@ -334,7 +343,7 @@ impl Table { for c in &r.cells { out.push('\t'); if let Some(v) = c.value { - out.push_str(&v.round_dp(2).to_string()); + out.push_str(&crate::fmt::round_display(v, 2).to_string()); } } out.push('\n'); @@ -2401,6 +2410,38 @@ mod tests { assert_eq!(prior(&st, NaiveDate::MIN, d(2026, 1, 1)), None); } + /// The change column: no percent of a zero or negative base. + #[test] + fn a_change_from_a_negative_base_has_no_percent() { + let table = |now: i64, prior: i64| { + let mut t = Table::new(vec!["Now".into(), "Prior".into()]); + t.row( + Kind::Line, + "Rent", + vec![Cell::of(Decimal::from(now)), Cell::of(Decimal::from(prior))], + ); + t.add_change(); + t + }; + // From a positive base: (150 - 100) / 100 = 50.0%. + assert_eq!( + table(150, 100).rows[0].cells[3].value, + Some(Decimal::new(500, 1)) + ); + // From a negative or zero base: a change, but no percent. + assert_eq!(table(-50, -100).rows[0].cells[3].value, None); + assert_eq!(table(50, 0).rows[0].cells[3].value, None); + // A share of negative income adds no column at all. + let mut t = Table::new(vec!["Now".into()]); + t.row( + Kind::Subtotal, + "Total income", + vec![Cell::of(Decimal::from(-100))], + ); + t.add_share_of_income(); + assert_eq!(t.columns.len(), 1); + } + /// too_many_columns: a split's column count, counted from the months /// (each started interval a column), only when past MAX_COLUMNS. #[test]