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
This commit is contained in:
1 parent
a414462be7
commit
a7d0c7f2d3
8 files changed
+166
-54
No files matched your search
@@ -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
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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<Decimal> {
|
||||
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.
|
||||
|
||||
@@ -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]
|
||||
|
||||
Reference in new issue
Block a user