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..f8480a31 100644 --- a/crates/ledger-gui/src/demo.rs +++ b/crates/ledger-gui/src/demo.rs @@ -788,7 +788,16 @@ 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); + // A booked figure, so the kernel's rounding and not the + // display's: ten percent to the cent, a half to the even + // cent, as these books have always been drawn. + let fee = ledger_core::kernel::round_places( + gross * Decimal::new(10, 2), + 2, + ledger_core::kernel::Rounding::HalfToEven, + ) + .expect("a tenth of a four-digit sale rounds to the cent") + + 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] diff --git a/crates/ledger-gui/tests/display_rounding.rs b/crates/ledger-gui/tests/display_rounding.rs new file mode 100644 index 00000000..5a4aa123 --- /dev/null +++ b/crates/ledger-gui/tests/display_rounding.rs @@ -0,0 +1,119 @@ +//! K-U9: one display rounding, and no float in a money path. +//! +//! The behavioural half uses the public formatting API. The source +//! half is a scoped grep: the display files that shorten or ratio +//! money must not name `round_dp` (they go through +//! `ledger_import::round_display` or `kernel::percent_of`), and a +//! float conversion of a decimal may appear only at the xlsx cell +//! boundary, where the cell itself is a binary double and the value +//! is written as a number only when it is exactly representable. + +use rust_decimal::Decimal; +use std::path::{Path, PathBuf}; +use std::str::FromStr; + +fn dec(s: &str) -> Decimal { + Decimal::from_str(s).unwrap() +} + +fn crate_src(krate: &str, file: &str) -> String { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + std::fs::read_to_string(root.join(krate).join("src").join(file)) + .unwrap_or_else(|e| panic!("{krate}/src/{file}: {e}")) +} + +fn all_rs(dir: &Path, out: &mut Vec) { + for e in std::fs::read_dir(dir).unwrap() { + let p = e.unwrap().path(); + if p.is_dir() { + all_rs(&p, out); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(p); + } + } +} + +/// Display rounding: half away from zero, never a negative zero. +#[test] +fn display_rounding_is_half_away_and_never_negative_zero() { + let r = ledger_import::round_display; + assert_eq!(r(dec("1.005"), 2), dec("1.01")); + assert_eq!(r(dec("-1.005"), 2), dec("-1.01")); + assert_eq!(r(dec("2.5"), 0), dec("3")); + assert_eq!(r(dec("-0.004"), 2).to_string(), "0.00"); + assert_eq!(ledger_import::format_amount(dec("-0.004")), "0.00"); + assert_eq!(ledger_import::format_amount(dec("-1.005")), "(1.01)"); + // The viewer re-exports the same function. + assert_eq!(ledger_gui::fmt::round_display(dec("1.005"), 2), dec("1.01")); +} + +/// A percentage of a zero or negative base is shown as nothing. +#[test] +fn a_percent_of_a_zero_or_negative_base_is_none() { + assert_eq!( + ledger_gui::fmt::pct_change(dec("200"), dec("250")), + Some(dec("25.0")) + ); + assert_eq!(ledger_gui::fmt::pct_change(dec("0"), dec("5")), None); + assert_eq!(ledger_gui::fmt::pct_change(dec("-100"), dec("-50")), None); +} + +/// No `round_dp` left in the display paths, and no float conversion +/// of a decimal outside the xlsx cell boundary. +#[test] +fn no_round_dp_or_float_conversion_in_money_display_paths() { + for (krate, file) in [ + ("ledger-gui", "fmt.rs"), + ("ledger-gui", "books.rs"), + ("ledger-gui", "demo.rs"), + ("ledger-gui", "pages/profit.rs"), + ("ledger-gui", "pages/reports.rs"), + ("ledger-gui", "pages/overview.rs"), + ("ledger-gui", "pages/cash.rs"), + ("ledger-gui", "pages/capital.rs"), + ("ledger-import", "report.rs"), + ("ledger-import", "pdf.rs"), + ("ledger-import", "xlsx.rs"), + ("ledger-import", "format.rs"), + ("ledger-package", "text.rs"), + ] { + assert!( + !crate_src(krate, file).contains("round_dp"), + "{krate}/src/{file} must use round_display / kernel rounding" + ); + } + // fmt's percent and compact paths (everything above `bytes`, which + // sizes a byte count, not money) name no float at all. + let fmt_src = crate_src("ledger-gui", "fmt.rs"); + let (money_half, _) = fmt_src + .split_once("pub fn bytes") + .expect("fmt::bytes exists"); + assert!( + !money_half.contains("f64"), + "fmt money paths must be Decimal" + ); + assert!( + !money_half.contains("f32"), + "fmt money paths must be Decimal" + ); + + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + for krate in [ + "ledger-gui", + "ledger-import", + "ledger-package", + "ledger-mcp", + ] { + let mut files = Vec::new(); + all_rs(&root.join(krate).join("src"), &mut files); + for f in files { + let text = std::fs::read_to_string(&f).unwrap(); + if text.contains("to_f64") { + assert!( + f.ends_with("xlsx.rs"), + "to_f64 only at the xlsx cell boundary: {f:?}" + ); + } + } + } +} diff --git a/crates/ledger-gui/tests/view_model.rs b/crates/ledger-gui/tests/view_model.rs index d513270c..c72801d7 100644 --- a/crates/ledger-gui/tests/view_model.rs +++ b/crates/ledger-gui/tests/view_model.rs @@ -324,9 +324,10 @@ fn origins_and_parties() { fn percent_change_and_tax_forms() { let d = |s: &str| s.parse::().unwrap(); assert_eq!(fmt::pct_change(d("0"), d("5")), None); - assert_eq!(fmt::pct_change(d("100"), d("150")), Some(50.0)); - assert_eq!(fmt::pct_change(d("200"), d("150")), Some(-25.0)); - assert_eq!(fmt::pct_change(d("-100"), d("-50")), Some(50.0)); + assert_eq!(fmt::pct_change(d("100"), d("150")), Some(d("50.0"))); + assert_eq!(fmt::pct_change(d("200"), d("150")), Some(d("-25.0"))); + // K-U9: no percent of a negative base (it misleads); Decimal, never f64. + assert_eq!(fmt::pct_change(d("-100"), d("-50")), None); use ledger_core::TaxForm::*; for (f, number) in [ (ScheduleC, "Schedule C"), diff --git a/crates/ledger-import/src/format.rs b/crates/ledger-import/src/format.rs new file mode 100644 index 00000000..629d04ff --- /dev/null +++ b/crates/ledger-import/src/format.rs @@ -0,0 +1,70 @@ +//! The one rounding for presentation: an amount rounded for display, +//! never for the books. Every renderer that shortens an amount to a +//! fixed number of places goes through [`round_display`], so a display +//! change never changes a booked figure and a booked figure never +//! changes because of a display change. +//! +//! ```text +//! GOAL: one definition of display rounding for every renderer. +//! SOURCE: CONVENTION (US accounting presentation: an amount shown to a +//! fixed number of places rounds half away from zero, as +//! crate::report::format_amount has always done). +//! INVARIANTS: +//! 1. round_display(amount, places) is amount rounded to `places` +//! decimal places, half away from zero, through the kernel's one +//! rounding primitive (ledger_core::kernel::round_places). +//! 2. Never a negative zero: a result that is zero is "0.00", never +//! "-0.00" and never "(0.00)". +//! 3. Display only: the result is for printing. Callers never book it. +//! SCENARIOS: +//! 1. IF 1.005 to two places: SHOULD be 1.01 (and -1.005, -1.01). +//! 2. IF -0.004 to two places: SHOULD be 0.00, never a negative zero. +//! 3. IF 2.5 to zero places: SHOULD be 3 (and -2.5, -3). +//! ``` + +use ledger_core::kernel::Rounding; +use rust_decimal::Decimal; + +/// `amount` rounded to `places` decimal places for display: half away +/// from zero, never a negative zero. See the module spec. +pub fn round_display(amount: Decimal, places: u32) -> Decimal { + match ledger_core::kernel::round_places(amount, places, Rounding::HalfAwayFromZero) { + Some(r) => r, + // Rounding to fewer places cannot grow an amount past Decimal's + // range in practice; past exact arithmetic, show the amount + // itself (with no negative zero) rather than a wrong figure. + None if amount.is_zero() => Decimal::ZERO, + None => amount, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::str::FromStr; + + fn dec(s: &str) -> Decimal { + Decimal::from_str(s).unwrap() + } + + #[test] + fn half_away_from_zero() { + assert_eq!(round_display(dec("1.005"), 2), dec("1.01")); + assert_eq!(round_display(dec("-1.005"), 2), dec("-1.01")); + assert_eq!(round_display(dec("2.5"), 0), dec("3")); + assert_eq!(round_display(dec("-2.5"), 0), dec("-3")); + assert_eq!(round_display(dec("1.004"), 2), dec("1.00")); + assert_eq!(round_display(dec("1234567.891"), 2), dec("1234567.89")); + } + + #[test] + fn never_a_negative_zero() { + for s in ["-0.004", "-0.00", "-0", "0"] { + let r = round_display(dec(s), 2); + assert_eq!(r, Decimal::ZERO, "{s}"); + assert!(!r.is_sign_negative(), "{s}"); + } + assert_eq!(round_display(dec("-0.004"), 2).to_string(), "0.00"); + assert_eq!(round_display(dec("-0.4"), 0).to_string(), "0"); + } +} diff --git a/crates/ledger-import/src/lib.rs b/crates/ledger-import/src/lib.rs index b382d937..49822aff 100644 --- a/crates/ledger-import/src/lib.rs +++ b/crates/ledger-import/src/lib.rs @@ -19,6 +19,7 @@ pub mod chart_csv; /// The one reader, now the `ledger-reader` crate (D-61), kept at its old path. pub use ledger_reader as extract; pub mod fonts; +pub mod format; pub mod iif; pub mod invoice_pdf; pub mod labels; @@ -32,6 +33,7 @@ pub use asset_register::{asset_register_pdf, asset_register_xlsx}; pub use bank_csv::{BankCsvError, BankTransaction, DateOrder, parse_bank_csv, parse_bank_csv_with}; pub use chart_csv::{ChartRow, parse_chart_csv}; pub use extract::{ExtractError, page_count, page_png, pdf_lines, pdf_text, text_of, xlsx_text}; +pub use format::round_display; pub use iif::{ Iif, IifAccount, IifChange, IifClass, IifError, IifField, LeftOut, MEMO_MAX, NAME_MAX, NUMBER_MAX, QbAccountType, iif_accounts, iif_classes, journal_to_iif, diff --git a/crates/ledger-import/src/pdf.rs b/crates/ledger-import/src/pdf.rs index 130d6d47..dd3485df 100644 --- a/crates/ledger-import/src/pdf.rs +++ b/crates/ledger-import/src/pdf.rs @@ -83,7 +83,7 @@ pub fn template_data(st: &Statement, meta: &ReportMeta) -> serde_json::Value { "currency": r.currency, "amounts": r.amounts.iter().enumerate().map(|(i, a)| a.map(|a| { if st.percent_from.is_some_and(|f| i >= f) { - let a = a.round_dp(1); + let a = crate::format::round_display(a, 1); let negative = a.is_sign_negative() && !a.is_zero(); return serde_json::json!({ "digits": format!("{}%", a.abs().normalize()), diff --git a/crates/ledger-import/src/report.rs b/crates/ledger-import/src/report.rs index 35407a0f..27771448 100644 --- a/crates/ledger-import/src/report.rs +++ b/crates/ledger-import/src/report.rs @@ -632,7 +632,7 @@ pub fn period_label(start: NaiveDate, end: NaiveDate) -> String { /// to the cent. /// ``` pub fn format_amount(d: Decimal) -> String { - let rounded = d.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointAwayFromZero); + let rounded = crate::format::round_display(d, 2); let negative = rounded.is_sign_negative() && !rounded.is_zero(); let fixed = format!("{:.2}", rounded.abs()); let (int, frac) = fixed.split_once('.').expect("two decimals"); @@ -664,7 +664,7 @@ pub struct AmountParts { /// Split an amount for aligned accounting display. Exact: no floats. pub fn amount_parts(d: Decimal) -> AmountParts { - let rounded = d.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointAwayFromZero); + let rounded = crate::format::round_display(d, 2); AmountParts { digits: format_amount(rounded.abs()), negative: rounded.is_sign_negative() && !rounded.is_zero(), diff --git a/crates/ledger-import/src/xlsx.rs b/crates/ledger-import/src/xlsx.rs index 6c2199c6..288fdfda 100644 --- a/crates/ledger-import/src/xlsx.rs +++ b/crates/ledger-import/src/xlsx.rs @@ -442,7 +442,7 @@ fn exact_text(d: Decimal) -> String { /// cents, at most 15 significant digits. None otherwise. fn exact_f64(d: Decimal) -> Option { use rust_decimal::prelude::ToPrimitive; - let cents = d.round_dp(2); + let cents = crate::format::round_display(d, 2); if cents != d || cents.abs() > Decimal::new(999_999_999_999_999, 2) { return None; } diff --git a/crates/ledger-package/src/text.rs b/crates/ledger-package/src/text.rs index 55dc48a0..188bb051 100644 --- a/crates/ledger-package/src/text.rs +++ b/crates/ledger-package/src/text.rs @@ -22,7 +22,10 @@ use rust_decimal::Decimal; /// "318.42", "1000.00". Padding only, never rounding: an exact amount with /// more places (an FX-converted line) keeps them. Never "-0". pub fn money(n: Decimal) -> String { - let mut n = if n.is_zero() { Decimal::ZERO } else { n }; + // Padding only, never rounding: the display rounding at the + // amount's own scale (at least two places) is the identity, and it + // is what drops a negative zero. + let mut n = ledger_import::round_display(n, n.scale().max(2)); if n.scale() < 2 { n.rescale(2); } @@ -42,6 +45,7 @@ pub fn total_text(total: Option) -> String { /// share, never on its spelling. pub fn share_text(n: Decimal) -> String { let mut n = n.normalize(); + n = ledger_import::round_display(n, n.scale().max(2)); if n.scale() < 2 { n.rescale(2); } diff --git a/docs/proofs/display.md b/docs/proofs/display.md new file mode 100644 index 00000000..4c83d944 --- /dev/null +++ b/docs/proofs/display.md @@ -0,0 +1,128 @@ +# K-U9: display rounding, and percentages in Decimal + +_Folded into `docs/verification.md` by the integrator; this note is the +unit's own record._ + +Kernel sweep unit U9 (`plan/kernel-sweep-audit.md` section 3, "display +rounding"). Display only: no kernel function, no Kani harness, no Lean +theorem (the audit and `docs/proofs/README.md` say so for U9). The +rounding it shares is the kernel's already-proved `round_places` +(K-U2, law 40); the percentages it shares are `kernel::percent_of` +(K-U6). + +## The API + +```rust +// ledger-import::format (re-exported at the crate root) +pub fn round_display(amount: Decimal, places: u32) -> Decimal +``` + +Half away from zero to `places`, through +`ledger_core::kernel::round_places(..., Rounding::HalfAwayFromZero)`, +never a negative zero. It is the rounding half of +`ledger-import::report::format_amount`, lifted out so every renderer +shares it: `format_amount` and `amount_parts` call it at two places, +`ledger-import::pdf`'s percent column at one place, +`ledger-import::xlsx::exact_f64` at two places (before its exactness +check), `ledger-package::text`'s `money`/`share_text` at the amount's +own scale (the identity there: padding only, never rounding, as those +functions promise), and `ledger-gui::fmt` re-exports it for the pages. + +## The percent rule (one rule for every percent) + +A percent of a zero or negative whole is `None`, and the page shows +nothing (a KPI tile keeps no sub-line) or "—" (a table cell). That is +`kernel::percent_of`'s rule, and K-U9 adopts it everywhere: + +- `ledger-gui::fmt::pct_change` returns `Option` (it was + `Option`, dividing money amounts in binary floating point): + `(now - prev) / prev * 100` to one place, half away from zero, via + `percent_of`. A negative `prev` gave a signed percent before; now + `None`. +- `ledger-gui::pages::profit::pct` (margins, shares of invoiced + income): `percent_of` at one place, half to even — the books' margin + mode, as `contribution_margin_pct` uses. A negative revenue base + gave a percent before; now `None`, shown as "—". +- `ledger-gui::pages::reports`' change column: was + `diff / base.abs() * 100`, a percent of a negative base with the sign + hidden; now `percent_of(diff, base, ...)`, `None` for base <= 0. + The "% of income" column likewise adds no column when total income + is zero or negative (it added none for zero before). +- `ledger-gui::pages::capital::percent`: a member's share is a stored + fraction, not a ratio of two amounts, so it stays exact decimal + multiplication by 100 with no rounding; only a negative zero is + dropped. No float was involved. + +## Sites routed + +- `ledger-import`: `report::format_amount`, `report::amount_parts`, + `pdf` percent column, `xlsx::exact_f64` — through `round_display`. +- `ledger-package::text::money`, `share_text` — through + `round_display` at their own scale (identity; see above). +- `ledger-gui::fmt::compact`: was `f64` (`try_into`, `{:.1}` prints). + Now decimal division by 1,000 / 1,000,000 and `round_display`. Two + displayed figures change, both f64 artefacts: 1,250,000 shows + "$1.3M" (was "$1.2M": 1.25 in binary is slightly under), 10,500 shows + "$11k" (was "$10k": float formatting rounds 10.5 to even). +- `ledger-gui::fmt::pct_change` and its caller + `pages/overview::change` ("▲ 12% vs …" text and the 0.5% colour + threshold): Decimal throughout. +- `pages/overview` runway months, `pages/cash` average net and runway, + `pages/profit` spending row, `pages/reports` change / share / TSV, + `books` monthly-burn average, `demo` platform fee: `round_dp(1|2)` + through `round_display` (checked division where the old code divided + raw under a guard). +- `books`' two share splits truncated to cents with `ToZero`: that is + a leftover policy, not display rounding, so it now goes through + `kernel::round_places(..., TowardZero)` as `truncate_cents`, with no + change of value. + +## Floats kept, with why + +- `ledger-gui::charts` (`f(Decimal) -> f64`, `ticks`, sparklines, + `pages/overview`/`cash` spark vectors, `widgets::Kpi::spark`): pixel + coordinates and axis scales computed for layout only. Every hover + and label that states a figure reads the original `Decimal` + (`fmt::dollars`, `fmt::compact`); no printed amount is computed in + a float. +- egui layout `f32`s (column widths, row heights), colour maths in + `schemes.rs`, image sizes in `receipts.rs`: geometry and colour, + never money. +- Time `f64`s (`app::since_update`, `widgets` timers, + `pages/reports::pdf_done`, `pages/transactions::since_update`): + egui's clock, never money. +- `fmt::bytes` (`n as f64`): a byte count for "12.3 KB", not money. +- `ledger-import::labels` geometry (`f64` millimetre/point layout), + `asset_register`'s life-in-months cell (`f64::from(months)`: a + count), `xlsx` entry-id cells (`as f64`: an id): layout and counts. +- `ledger-import::xlsx::exact_f64` (`to_f64`): the one sanctioned + conversion — an xlsx cell is a binary double, and a value is + written as a number only when it is whole cents of at most 15 + significant digits, exactly representable; anything else is text. +- `ledger-mcp::types` `visit_f64`: serde's visitor signature for + refusing a float TIN, not a computation. +- `ledger-import::templates::equal_shares`: owner-percentage template + (audit class (c)), last-absorbs so the shares sum to 100; not a + display rounding of a money amount, left as is. + +## Tests + +- `crates/ledger-import/src/format.rs`: half away from zero at ties, + never a negative zero. +- `ledger-gui::fmt` tests: `pct_change` decimal-or-none (zero and + negative bases), `compact` decimal ties. +- `ledger-gui::pages::profit` tests: no percent of a negative base. +- `ledger-gui::pages::reports` tests: the change column has no + percent from a zero or negative base; no "% of income" column for + negative income. +- `crates/ledger-gui/tests/display_rounding.rs`: the rules through + the public API, plus a scoped source check (no `round_dp` in the + display files; no `f64` in `fmt`'s money half; `to_f64` only in + `xlsx.rs`). + +No golden changes. Displayed values that changed are the two +`compact` ties above and the percents of negative bases (now "—" / +no sub-line instead of a signed figure). One existing test encoded +the old negative-base percent (`ledger-gui/tests/view_model.rs`: +`pct_change(-100, -50)` was `Some(50.0)`); it now expects `None`, +per the rule above.