refactor(display): one rounding for presentation

Move format_amount's rounding half (half away from zero, never a negative zero) into ledger-import::format::round_display, through the kernel's round_places. format_amount, amount_parts, the PDF percent column, xlsx's exact_f64 and ledger-package's text padding all call it, so a display change never changes a booked figure.

Co-Authored-By: Muse Wonder 1.0
This commit is contained in:
swaitsandMuse Wonder 1.0 committed 2026-11-09 18:54:17 -07:00
1 parent 4da1c5b30f
commit a414462be7
6 files changed
+81 -5

No files matched your search

+70
View File
@@ -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");
}
}
+2
View File
@@ -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,
+1 -1
View File
@@ -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()),
+2 -2
View File
@@ -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(),
+1 -1
View File
@@ -442,7 +442,7 @@ fn exact_text(d: Decimal) -> String {
/// cents, at most 15 significant digits. None otherwise.
fn exact_f64(d: Decimal) -> Option<f64> {
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;
}
+5 -1
View File
@@ -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<Decimal>) -> 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);
}