From 74943fb6992147defc45b709d233bbddb0ae7acb Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 13:37:48 -0700 Subject: [PATCH] refactor(core): one rounding primitive, round_step, in the kernel Every money round_dp*/rescale in ledger-core now goes through kernel::round_step: amount to a whole multiple of a step, in a named mode (half away, half even, toward zero, toward negative infinity), exact integer arithmetic on Decimal mantissas and scales, None instead of a panic, no negative zero. The call sites use round_places, which reproduces Decimal::round_dp_with_strategy exactly (value, scale and its early return), and add_line_fx uses round_minor for the base currency's smallest unit. This is a refactor: every site produces exactly what it produced before, so no golden changes. The schedules' monthly-even plan keeps its two-place cent rule: moving it to the currency's minor unit is K-U5's decision (D-72), not this behaviour-preserving unit. The remaining rescales (money.rs's display padding, the contribution margin's one place) are formatting, not rounding, and stay. Co-Authored-By: DeepSeek V4.1 Flash --- crates/ledger-core/src/cashflow.rs | 5 +- crates/ledger-core/src/conventions.rs | 6 +- crates/ledger-core/src/form1099.rs | 9 +- crates/ledger-core/src/k1.rs | 7 +- crates/ledger-core/src/kernel/entries.rs | 16 ++ crates/ledger-core/src/kernel/round.rs | 298 ++++++++++++++++++++++- crates/ledger-core/src/ledger.rs | 11 +- crates/ledger-core/src/periods.rs | 21 +- crates/ledger-core/src/reports.rs | 12 +- crates/ledger-core/src/schedules.rs | 15 +- crates/ledger-core/src/shares.rs | 4 +- crates/ledger-core/src/tax_capital.rs | 12 +- 12 files changed, 375 insertions(+), 41 deletions(-) diff --git a/crates/ledger-core/src/cashflow.rs b/crates/ledger-core/src/cashflow.rs index 0c4b52c6..e478c067 100644 --- a/crates/ledger-core/src/cashflow.rs +++ b/crates/ledger-core/src/cashflow.rs @@ -1720,8 +1720,9 @@ fn split_part( let part = amount .checked_mul(ours) .and_then(|x| x.checked_div(whole)) - .ok_or_else(|| too_large("a payment's government part"))? - .round_dp_with_strategy(places, rust_decimal::RoundingStrategy::MidpointNearestEven); + .ok_or_else(|| too_large("a payment's government part"))?; + let part = crate::kernel::round_places(part, places, crate::kernel::Rounding::HalfToEven) + .ok_or_else(|| too_large("a payment's government part"))?; let rest = amount .checked_sub(part) .ok_or_else(|| too_large("a payment's government part"))?; diff --git a/crates/ledger-core/src/conventions.rs b/crates/ledger-core/src/conventions.rs index 011d9cb6..65d8a794 100644 --- a/crates/ledger-core/src/conventions.rs +++ b/crates/ledger-core/src/conventions.rs @@ -454,7 +454,7 @@ pub fn check_id(id: &str) -> Result<(), String> { /// ([`crate::kernel::apportion`]): the parts sum to `amount` exactly /// (INVARIANT 2). pub fn split(amount: Decimal, shares: &[Decimal], places: Option) -> Option> { - use rust_decimal::RoundingStrategy::ToZero; + use crate::kernel::{Rounding, round_places}; let exact: Vec = shares .iter() .map(|s| amount.checked_mul(*s)) @@ -466,8 +466,8 @@ pub fn split(amount: Decimal, shares: &[Decimal], places: Option) -> Option }; let mut parts: Vec = exact .iter() - .map(|e| e.round_dp_with_strategy(places, ToZero)) - .collect(); + .map(|e| round_places(*e, places, Rounding::TowardZero)) + .collect::>()?; let remainders: Vec = exact .iter() .zip(&parts) diff --git a/crates/ledger-core/src/form1099.rs b/crates/ledger-core/src/form1099.rs index 03d453ce..6724229a 100644 --- a/crates/ledger-core/src/form1099.rs +++ b/crates/ledger-core/src/form1099.rs @@ -728,7 +728,11 @@ fn vendor_part(payment: Decimal, share: Decimal, target: Decimal) -> Result Result<[Decimal; 3], LedgerError> // exactly (the division alone rounds past 28 digits). let num = b[i].abs().checked_mul(av).ok_or_else(too_large)?; let q = num.checked_div(ap).ok_or_else(too_large)?; - let mut part = q.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::ToZero); + let mut part = + kernel::round_places(q, 2, kernel::Rounding::TowardZero).ok_or_else(too_large)?; while times(part)? > num { part -= cent; } diff --git a/crates/ledger-core/src/k1.rs b/crates/ledger-core/src/k1.rs index 72ab31df..622ec80d 100644 --- a/crates/ledger-core/src/k1.rs +++ b/crates/ledger-core/src/k1.rs @@ -314,7 +314,7 @@ pub(crate) fn share_property( credits: &[Decimal], places: u32, ) -> Result, LedgerError> { - use rust_decimal::RoundingStrategy::ToZero; + use crate::kernel::{Rounding, round_places}; let too_large = || LedgerError::TooLargeToCompute("a member's share of contributed property".into()); let total = credits @@ -334,8 +334,9 @@ pub(crate) fn share_property( .ok_or_else(too_large)?; let mut parts: Vec = exact .iter() - .map(|x| x.round_dp_with_strategy(places, ToZero)) - .collect(); + .map(|x| round_places(*x, places, Rounding::TowardZero)) + .collect::>() + .ok_or_else(too_large)?; let remainders: Vec = exact.iter().zip(&parts).map(|(x, p)| x - p).collect(); crate::kernel::apportion(whole, &mut parts, &remainders, Decimal::new(1, places)) .expect("each part is short by under a unit, so the shortfall is under a unit per member"); diff --git a/crates/ledger-core/src/kernel/entries.rs b/crates/ledger-core/src/kernel/entries.rs index 9048ffb2..6af7f5c9 100644 --- a/crates/ledger-core/src/kernel/entries.rs +++ b/crates/ledger-core/src/kernel/entries.rs @@ -2,6 +2,7 @@ //! grouping the lines of an entry or a book, unchanged in U0. The laws it //! serves are listed at the module root, [`super`]. +use super::round::Rounding; use crate::assets::BasisRule; use crate::{AccountType, Side}; use rust_decimal::Decimal; @@ -41,6 +42,12 @@ pub trait Amount: Copy + Ord { /// B-21), whose shares are added exactly and rounded once, never /// share by share. fn checked_div_round_cent(self, rhs: Self) -> Option; + /// `self` rounded to a whole multiple of `step`, in `mode`; `None` + /// when `step` is not positive or the result cannot be represented. + /// + /// The instantiation of [`crate::kernel::round_step`], which the call + /// sites use; a machine integer is already a whole smallest unit. + fn checked_round_to_step(self, step: Self, mode: Rounding) -> Option; /// `self - rhs`, or `None` when it cannot be represented exactly. fn checked_sub(self, rhs: Self) -> Option { @@ -148,6 +155,9 @@ impl Amount for Decimal { let signed = if negative { -signed_mag } else { signed_mag }; Decimal::try_from_i128_with_scale(signed, scale).ok() } + fn checked_round_to_step(self, step: Self, mode: Rounding) -> Option { + super::round::round_decimal_to_step(self, step, mode) + } } impl Amount for i32 { @@ -196,6 +206,9 @@ impl Amount for i32 { q.checked_sub(1) } } + fn checked_round_to_step(self, step: Self, mode: Rounding) -> Option { + super::round::round_i32_to_step(self, step, mode) + } } impl Amount for i64 { @@ -245,6 +258,9 @@ impl Amount for i64 { q.checked_sub(1) } } + fn checked_round_to_step(self, step: Self, mode: Rounding) -> Option { + super::round::round_i64_to_step(self, step, mode) + } } /// Why the kernel rejected an entry's lines. diff --git a/crates/ledger-core/src/kernel/round.rs b/crates/ledger-core/src/kernel/round.rs index e412a684..c8809540 100644 --- a/crates/ledger-core/src/kernel/round.rs +++ b/crates/ledger-core/src/kernel/round.rs @@ -1,5 +1,293 @@ -//! U2: one rounding primitive, the single place money is rounded to a step (kernel sweep). -//! -//! Empty in U0: the unit adds its arithmetic here, in this file alone, so -//! no two sweep units ever edit the same file. The module root re-exports -//! it, keeping every path `crate::kernel::foo`. +//! The rounding primitive: money rounded to a whole multiple of a unit, +//! once, in a named mode. The kernel sweep's U2 (plan/kernel-sweep-audit.md +//! section 3) routes every `round_dp*`/`rescale` on money through it, so +//! the engine has one definition of "round" and no call site invents a +//! second. + +use crate::Currency; +use crate::kernel::Amount; +use rust_decimal::Decimal; + +/// How a value is rounded to a step. Only the modes the engine uses today +/// are here; a new mode is a new match arm in each [`Amount`] +/// instantiation, never a silent default. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Rounding { + /// Nearest multiple; an exact half rounds away from zero + /// (2.5 -> 3, -2.5 -> -3). The FX booking rule (B-3). + HalfAwayFromZero, + /// Nearest multiple; an exact half rounds to the even multiple + /// (2.5 -> 2, 3.5 -> 4). Rust's `Decimal::round_dp`. + HalfToEven, + /// Down in magnitude, toward zero (2.9 -> 2, -2.9 -> -2). + TowardZero, + /// Down, toward negative infinity (2.9 -> 2, -2.9 -> -3). + TowardNegativeInfinity, +} + +/// `amount` rounded to a whole multiple of `step`, in `mode`. +/// +/// ```text +/// GOAL: one rounding primitive: money is rounded to a whole multiple of a +/// unit, once, with the mode named at the call. +/// SOURCE: docs/spec/claims/ledger.md B-3 (a ledger in one money holds no +/// fractions of its smallest unit; FX books the base currency's +/// minor unit, half away from zero), claims/entry.md B-21 (exact +/// amounts in the books; round only where a rule says to), and +/// claims/ledger.md B-32; the call sites' own rules (B-13, B-14, +/// B-15, B-16, B-19, B-35, B-36, B-37); owner decision D-69 (the +/// laws live once, in bookspec's Lean). +/// INVARIANTS: +/// 1. Some(r) is a whole multiple of step: r = n x step for an integer +/// n, with step > 0. None when step <= 0 or nothing can hold the +/// result. +/// 2. HalfAwayFromZero and HalfToEven are nearest: |r - amount| <= +/// step/2; at exactly half, the mode's tie rule picks the multiple. +/// 3. TowardZero never increases magnitude: |r| <= |amount| and +/// |r - amount| < step. +/// 4. TowardNegativeInfinity is the floor: r <= amount < r + step. +/// 5. Idempotent: round(round(x)) = round(x) for the same step and mode. +/// 6. The symmetric modes (HalfAwayFromZero, HalfToEven, TowardZero) are +/// odd: round(-x) = -round(x). No mode ever flips the sign (a +/// non-zero amount never rounds to the other side of zero). +/// 7. Never a negative zero: a result that is zero is +0. Never a panic; +/// overflow and an impossible step are None. +/// SCENARIOS: +/// 1. IF 1.005 to the cent, HalfAwayFromZero: SHOULD be 1.01. +/// 2. IF 1.005 to the cent, HalfToEven: SHOULD be 1.00 (100 is even). +/// 3. IF -1.005 to the cent, TowardNegativeInfinity: SHOULD be -1.01. +/// 4. IF 0.004 to the cent, either half mode: SHOULD be 0 (not -0). +/// 5. IF the step is zero or negative: SHOULD be None, never a guess. +/// ``` +pub fn round_step(amount: T, step: T, mode: Rounding) -> Option { + amount.checked_round_to_step(step, mode) +} + +/// `amount` rounded to `places` decimal places in `mode`, exactly as +/// `Decimal::round_dp_with_strategy` does today: an amount carrying no +/// more places than `places` is returned unchanged, and otherwise the +/// result carries exactly `places` places. This is the behaviour-preserving +/// wrapper the call sites use while U2 proves `round_step` underneath +/// them; it is not a second rounding rule. +pub fn round_places(amount: Decimal, places: u32, mode: Rounding) -> Option { + if amount.is_zero() { + // Keep round_dp's scale, but never its negative zero. + return Decimal::try_from_i128_with_scale(0, amount.scale().min(places)).ok(); + } + if amount.scale() <= places { + return Some(amount); + } + let step = Decimal::try_from_i128_with_scale(1, places).ok()?; + let rounded = round_step(amount, step, mode)?; + if rounded.is_zero() { + // Keep the places (a report prints "0.00"), never a negative zero. + return Decimal::try_from_i128_with_scale(0, places).ok(); + } + let mut rounded = rounded; + if rounded.scale() != places { + // Round_dp_with_strategy returns the target scale even when the + // value is a whole multiple (1.200 at two places is 1.20), and + // round_step returns an exact multiple unchanged. + rounded.rescale(places); + } + Some(rounded) +} + +/// `amount` rounded to whole `currency` minor units in `mode`: cents for +/// USD, whole yen for JPY, thousandths for KWD. A currency ISO 4217 gives +/// no minor unit (gold, SDRs) is returned exactly, as the FX booking rule +/// has always done (B-3). +pub fn round_minor(amount: Decimal, currency: Currency, mode: Rounding) -> Option { + match currency.minor_units() { + Some(places) => round_places(amount, places, mode), + None => Some(amount), + } +} + +/// The `Decimal` instantiation of [`Amount::checked_round_to_step`]: exact +/// integer arithmetic on the two mantissas and scales, so no intermediate +/// `amount / step` is ever rounded by `Decimal`'s 28-digit division. The +/// quotient is rounded in integer space and multiplied by the step's +/// mantissa once; reduction by trailing zeros (as in +/// `checked_div_round_cent`) makes the result fit Decimal's 96-bit +/// mantissa when the value allows it. +pub(crate) fn round_decimal_to_step( + amount: Decimal, + step: Decimal, + mode: Rounding, +) -> Option { + if step <= Decimal::ZERO { + return None; + } + if amount.is_zero() { + return Some(Decimal::ZERO); + } + let negative = amount.is_sign_negative(); + let a = amount.mantissa().unsigned_abs(); + let b = step.mantissa().unsigned_abs(); + let exponent = i64::from(step.scale()) - i64::from(amount.scale()); + // An exact multiple is already rounded. That case also covers the one + // the integer quotient cannot name: a step far finer than the amount + // (1e28 as 1e-20 steps is a 48-digit count, but the value is 1e28). + if is_exact_multiple(a, b, exponent) { + return Some(amount); + } + + let (mut floor, round_up) = if exponent >= 0 { + let exp = u32::try_from(exponent).ok()?; + let power = 10u128.checked_pow(exp)?; + let whole = a / b; + let mut remainder = a % b; + let mut fraction = 0u128; + for _ in 0..exp { + remainder = remainder.checked_mul(10)?; + fraction = fraction.checked_mul(10)?.checked_add(remainder / b)?; + remainder %= b; + } + let floor = whole.checked_mul(power)?.checked_add(fraction)?; + let twice = remainder.checked_mul(2)?; + let round_up = match mode { + Rounding::TowardZero => false, + Rounding::TowardNegativeInfinity => negative && remainder != 0, + Rounding::HalfAwayFromZero => twice >= b, + Rounding::HalfToEven => twice > b || (twice == b && !floor.is_multiple_of(2)), + }; + (floor, round_up) + } else { + let places = u32::try_from(-exponent).ok()?; + let power = 10u128.checked_pow(places)?; + let quotient = a / b; + let remainder = a % b; + let digit = quotient % power; + let floor = quotient / power; + let twice = digit.checked_mul(2)?; + let round_up = match mode { + Rounding::TowardZero => false, + Rounding::TowardNegativeInfinity => negative && (digit != 0 || remainder != 0), + Rounding::HalfAwayFromZero => twice >= power, + Rounding::HalfToEven => { + twice > power || (twice == power && (remainder != 0 || !floor.is_multiple_of(2))) + } + }; + (floor, round_up) + }; + + if round_up { + floor = floor.checked_add(1)?; + } + let mut mantissa = floor.checked_mul(b)?; + if mantissa == 0 { + // Never a negative zero: money never prints "-0". + return Some(Decimal::ZERO); + } + let max = Decimal::MAX.mantissa().unsigned_abs(); + let mut scale = step.scale(); + while mantissa > max { + if scale == 0 || !mantissa.is_multiple_of(10) { + return None; + } + mantissa /= 10; + scale -= 1; + } + let signed = i128::try_from(mantissa).ok()?; + let signed = if negative { -signed } else { signed }; + Decimal::try_from_i128_with_scale(signed, scale).ok() +} + +/// True when `a x 10^exponent` (or `a / 10^-exponent`) is a whole multiple +/// of `b`, without ever materialising the product: only remainders below +/// `b` (under Decimal's 96-bit mantissa) are multiplied by ten. +fn is_exact_multiple(a: u128, b: u128, exponent: i64) -> bool { + if exponent >= 0 { + let mut remainder = a % b; + for _ in 0..exponent { + if remainder == 0 { + return true; + } + remainder = (remainder * 10) % b; + } + remainder == 0 + } else { + let places = u32::try_from(-exponent).unwrap_or(u32::MAX); + let Some(power) = 10u128.checked_pow(places) else { + return false; + }; + if !a.is_multiple_of(power) { + return false; + } + (a / power).is_multiple_of(b) + } +} + +/// The `i64` instantiation: a machine integer is already a whole smallest +/// unit, so the step is a whole number of them (a Kani model, never money +/// with a fractional unit). +pub(crate) fn round_i64_to_step(value: i64, step: i64, mode: Rounding) -> Option { + if step <= 0 { + return None; + } + let negative = value < 0; + let magnitude = value.unsigned_abs(); + let divisor = step.unsigned_abs(); + let floor = magnitude / divisor; + let remainder = magnitude % divisor; + let twice = remainder.checked_mul(2)?; + let round_up = match mode { + Rounding::TowardZero => false, + Rounding::TowardNegativeInfinity => negative && remainder != 0, + Rounding::HalfAwayFromZero => twice >= divisor, + Rounding::HalfToEven => twice > divisor || (twice == divisor && !floor.is_multiple_of(2)), + }; + let count = if round_up { + floor.checked_add(1)? + } else { + floor + }; + let magnitude = count.checked_mul(divisor)?; + let limit = if negative { + 1u64 << 63 + } else { + i64::MAX as u64 + }; + if magnitude > limit { + return None; + } + let signed = magnitude as i64; + Some(if negative { -signed } else { signed }) +} + +/// The `i32` instantiation, the proof model's smaller type: the same rule +/// in 32 bits. +pub(crate) fn round_i32_to_step(value: i32, step: i32, mode: Rounding) -> Option { + if step <= 0 { + return None; + } + let negative = value < 0; + let magnitude = value.unsigned_abs(); + let divisor = step.unsigned_abs(); + let floor = magnitude / divisor; + let remainder = magnitude % divisor; + let twice = remainder.checked_mul(2)?; + let round_up = match mode { + Rounding::TowardZero => false, + Rounding::TowardNegativeInfinity => negative && remainder != 0, + Rounding::HalfAwayFromZero => twice >= divisor, + Rounding::HalfToEven => twice > divisor || (twice == divisor && !floor.is_multiple_of(2)), + }; + let count = if round_up { + floor.checked_add(1)? + } else { + floor + }; + let magnitude = count.checked_mul(divisor)?; + let limit = if negative { + 1u32 << 31 + } else { + i32::MAX as u32 + }; + if magnitude > limit { + return None; + } + let signed = magnitude as i32; + Some(if negative { -signed } else { signed }) +} diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index cf753637..6358a1c1 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -1871,11 +1871,12 @@ impl Ledger { // away from zero: a ledger in one money holds no fractions of its // smallest unit (rules.md B-3; DECISION, owner 2026-10-13, after // the GnuCash cross-check found the difference). - let base_amount = match self.base_currency.minor_units() { - Some(dp) => exact - .round_dp_with_strategy(dp, rust_decimal::RoundingStrategy::MidpointAwayFromZero), - None => exact, - }; + let base_amount = crate::kernel::round_minor( + exact, + self.base_currency, + crate::kernel::Rounding::HalfAwayFromZero, + ) + .ok_or(LedgerError::AmountOutOfRange)?; if base_amount <= Decimal::ZERO { return Err(LedgerError::InvalidFxRate(fx_rate)); } diff --git a/crates/ledger-core/src/periods.rs b/crates/ledger-core/src/periods.rs index 06888e4c..a1f92ee7 100644 --- a/crates/ledger-core/src/periods.rs +++ b/crates/ledger-core/src/periods.rs @@ -124,12 +124,15 @@ pub fn allocate( amount: rust_decimal::Decimal, shares: &[rust_decimal::Decimal], ) -> Vec { - use rust_decimal::{Decimal, RoundingStrategy::ToZero}; + use rust_decimal::Decimal; let magnitude = amount.abs(); let exact: Vec = shares.iter().map(|s| magnitude * s).collect(); let mut parts: Vec = exact .iter() - .map(|e| e.round_dp_with_strategy(2, ToZero)) + .map(|e| { + crate::kernel::round_places(*e, 2, crate::kernel::Rounding::TowardZero) + .expect("a cent place of a representable amount is representable") + }) .collect(); let remainders: Vec = exact.iter().zip(&parts).map(|(e, p)| e - p).collect(); crate::kernel::apportion(magnitude, &mut parts, &remainders, Decimal::new(1, 2)) @@ -149,10 +152,13 @@ pub fn allocate_last_absorbs( amount: rust_decimal::Decimal, shares: &[rust_decimal::Decimal], ) -> Vec { - use rust_decimal::RoundingStrategy::MidpointAwayFromZero; + use crate::kernel::{Rounding, round_places}; let mut parts: Vec<_> = shares .iter() - .map(|s| (amount * s).round_dp_with_strategy(2, MidpointAwayFromZero)) + .map(|s| { + round_places(amount * s, 2, Rounding::HalfAwayFromZero) + .expect("a cent place of a representable amount is representable") + }) .collect(); crate::kernel::plug_last(amount, &mut parts).expect("allocated amounts are in range"); parts @@ -205,7 +211,8 @@ pub fn allocate_cumulative( given: &[rust_decimal::Decimal], places: u32, ) -> Result, LedgerError> { - use rust_decimal::{Decimal, RoundingStrategy::ToZero}; + use crate::kernel::{Rounding, round_places}; + use rust_decimal::Decimal; if shares.len() != given.len() { return Err(LedgerError::InvalidMembers(format!( "{} shares but {} earlier parts", @@ -236,7 +243,9 @@ pub fn allocate_cumulative( "a member's share {share} of {magnitude}, to its last digit," )) })?; - let floor = exact.round_dp_with_strategy(places, ToZero); + let floor = round_places(exact, places, Rounding::TowardZero).ok_or_else(|| { + LedgerError::TooLargeToCompute(format!("a member's share {share} of {magnitude}")) + })?; parts.push(floor); remainders.push(exact - floor); } diff --git a/crates/ledger-core/src/reports.rs b/crates/ledger-core/src/reports.rs index 01c96cdd..125417fb 100644 --- a/crates/ledger-core/src/reports.rs +++ b/crates/ledger-core/src/reports.rs @@ -626,10 +626,14 @@ pub fn contribution_margin_pct(contribution: Decimal, revenue: Decimal) -> Optio if revenue <= Decimal::ZERO { return None; } - let mut x = contribution - .checked_div(revenue)? - .checked_mul(Decimal::ONE_HUNDRED)? - .round_dp_with_strategy(1, rust_decimal::RoundingStrategy::MidpointNearestEven); + let mut x = crate::kernel::round_places( + contribution + .checked_div(revenue)? + .checked_mul(Decimal::ONE_HUNDRED)?, + 1, + crate::kernel::Rounding::HalfToEven, + )?; + // Display padding only: the margin always prints its one place. x.rescale(1); Some(x) } diff --git a/crates/ledger-core/src/schedules.rs b/crates/ledger-core/src/schedules.rs index 468a5b9d..139542e8 100644 --- a/crates/ledger-core/src/schedules.rs +++ b/crates/ledger-core/src/schedules.rs @@ -193,10 +193,17 @@ pub fn amortization_plan( if total.abs() >= EXACT_LIMIT { return Err(too_large()); } - let each = total - .checked_div(Decimal::from(months)) - .ok_or_else(too_large)? - .round_dp(2); + // Two places whatever the currency: the monthly-even plan's cent rule is + // replay-frozen, and moving it to the currency's minor unit is K-U5 + // (owner decision D-72), not this behaviour-preserving rounding unit. + let each = kernel::round_places( + total + .checked_div(Decimal::from(months)) + .ok_or_else(too_large)?, + 2, + kernel::Rounding::HalfToEven, + ) + .ok_or_else(too_large)?; let first = start .with_day(1) .ok_or(LedgerError::DateOutOfRange(start))?; diff --git a/crates/ledger-core/src/shares.rs b/crates/ledger-core/src/shares.rs index fc056883..550b6ae0 100644 --- a/crates/ledger-core/src/shares.rs +++ b/crates/ledger-core/src/shares.rs @@ -284,7 +284,7 @@ fn checked_sum(values: impl IntoIterator) -> Option { /// part rounded toward zero to the cent, the cents left over to the first. /// None when a product or sum is past exact arithmetic. fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Option> { - use rust_decimal::RoundingStrategy::ToZero; + use crate::kernel::{Rounding, round_places}; let total = checked_sum(weights.iter().copied())?; if weights.is_empty() || total.is_zero() { return Some(vec![Decimal::ZERO; weights.len()]); @@ -295,7 +295,7 @@ fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Option> magnitude .checked_mul(*w) .and_then(|x| x.checked_div(total)) - .map(|x| x.round_dp_with_strategy(2, ToZero)) + .and_then(|x| round_places(x, 2, Rounding::TowardZero)) }) .collect::>()?; let left = magnitude.checked_sub(checked_sum(parts.iter().copied())?)?; diff --git a/crates/ledger-core/src/tax_capital.rs b/crates/ledger-core/src/tax_capital.rs index 85b9a708..b934c25e 100644 --- a/crates/ledger-core/src/tax_capital.rs +++ b/crates/ledger-core/src/tax_capital.rs @@ -456,7 +456,7 @@ impl RunningSplit { whole: Decimal, weights: &[Decimal], ) -> Result, LedgerError> { - use rust_decimal::RoundingStrategy::ToNegativeInfinity; + use crate::kernel::{Rounding, round_places}; let n = self.given.len(); let Some(sum) = self.weight_sum(weights)? else { return Ok(vec![Decimal::ZERO; n]); @@ -482,12 +482,14 @@ impl RunningSplit { // rounded down to the cent, what rounding took its remainder. let snapped: Vec = exact .iter() - .map(|x| (x * sign).round_dp(EXACT_PLACES)) - .collect(); + .map(|x| round_places(x * sign, EXACT_PLACES, Rounding::HalfToEven)) + .collect::>() + .ok_or_else(too_large)?; let mut parts: Vec = snapped .iter() - .map(|x| x.round_dp_with_strategy(2, ToNegativeInfinity)) - .collect(); + .map(|x| round_places(*x, 2, Rounding::TowardNegativeInfinity)) + .collect::>() + .ok_or_else(too_large)?; let remainders: Vec = snapped.iter().zip(&parts).map(|(x, p)| x - p).collect(); let given: Vec = self.given.iter().map(|g| g * sign).collect(); crate::kernel::apportion_cumulative(