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 <noreply@opencode.ai>
This commit is contained in:
swaitsandDeepSeek V4.1 Flash committed 2026-11-08 13:37:48 -07:00
1 parent 75c666a7ce
commit 74943fb699
12 files changed
+375 -41

No files matched your search

+3 -2
View File
@@ -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"))?;
+3 -3
View File
@@ -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<u32>) -> Option<Vec<Decimal>> {
use rust_decimal::RoundingStrategy::ToZero;
use crate::kernel::{Rounding, round_places};
let exact: Vec<Decimal> = shares
.iter()
.map(|s| amount.checked_mul(*s))
@@ -466,8 +466,8 @@ pub fn split(amount: Decimal, shares: &[Decimal], places: Option<u32>) -> Option
};
let mut parts: Vec<Decimal> = exact
.iter()
.map(|e| e.round_dp_with_strategy(places, ToZero))
.collect();
.map(|e| round_places(*e, places, Rounding::TowardZero))
.collect::<Option<_>>()?;
let remainders: Vec<Decimal> = exact
.iter()
.zip(&parts)
+7 -2
View File
@@ -728,7 +728,11 @@ fn vendor_part(payment: Decimal, share: Decimal, target: Decimal) -> Result<Deci
"a vendor's share ({share}) of a payment of {payment}"
))
})?;
Ok(scaled.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointAwayFromZero))
kernel::round_places(scaled, 2, kernel::Rounding::HalfAwayFromZero).ok_or_else(|| {
LedgerError::TooLargeToCompute(format!(
"a vendor's share ({share}) of a payment of {payment}"
))
})
}
}
@@ -761,7 +765,8 @@ fn split_share(b: [Decimal; 3], v: Decimal) -> 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;
}
+4 -3
View File
@@ -314,7 +314,7 @@ pub(crate) fn share_property(
credits: &[Decimal],
places: u32,
) -> Result<Vec<Decimal>, 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<Decimal> = exact
.iter()
.map(|x| x.round_dp_with_strategy(places, ToZero))
.collect();
.map(|x| round_places(*x, places, Rounding::TowardZero))
.collect::<Option<_>>()
.ok_or_else(too_large)?;
let remainders: Vec<Decimal> = 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");
+16
View File
@@ -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>;
/// `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>;
/// `self - rhs`, or `None` when it cannot be represented exactly.
fn checked_sub(self, rhs: Self) -> Option<Self> {
@@ -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<Self> {
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<Self> {
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<Self> {
super::round::round_i64_to_step(self, step, mode)
}
}
/// Why the kernel rejected an entry's lines.
+293 -5
View File
@@ -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<T: Amount>(amount: T, step: T, mode: Rounding) -> Option<T> {
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<Decimal> {
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<Decimal> {
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<Decimal> {
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<i64> {
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<i32> {
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 })
}
+6 -5
View File
@@ -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));
}
+15 -6
View File
@@ -124,12 +124,15 @@ pub fn allocate(
amount: rust_decimal::Decimal,
shares: &[rust_decimal::Decimal],
) -> Vec<rust_decimal::Decimal> {
use rust_decimal::{Decimal, RoundingStrategy::ToZero};
use rust_decimal::Decimal;
let magnitude = amount.abs();
let exact: Vec<Decimal> = shares.iter().map(|s| magnitude * s).collect();
let mut parts: Vec<Decimal> = 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<Decimal> = 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<rust_decimal::Decimal> {
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<Vec<rust_decimal::Decimal>, 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);
}
+8 -4
View File
@@ -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)
}
+11 -4
View File
@@ -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))?;
+2 -2
View File
@@ -284,7 +284,7 @@ fn checked_sum(values: impl IntoIterator<Item = Decimal>) -> Option<Decimal> {
/// 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<Vec<Decimal>> {
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<Vec<Decimal>>
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::<Option<_>>()?;
let left = magnitude.checked_sub(checked_sum(parts.iter().copied())?)?;
+7 -5
View File
@@ -456,7 +456,7 @@ impl RunningSplit {
whole: Decimal,
weights: &[Decimal],
) -> Result<Vec<Decimal>, 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<Decimal> = exact
.iter()
.map(|x| (x * sign).round_dp(EXACT_PLACES))
.collect();
.map(|x| round_places(x * sign, EXACT_PLACES, Rounding::HalfToEven))
.collect::<Option<_>>()
.ok_or_else(too_large)?;
let mut parts: Vec<Decimal> = snapped
.iter()
.map(|x| x.round_dp_with_strategy(2, ToNegativeInfinity))
.collect();
.map(|x| round_places(*x, 2, Rounding::TowardNegativeInfinity))
.collect::<Option<_>>()
.ok_or_else(too_large)?;
let remainders: Vec<Decimal> = snapped.iter().zip(&parts).map(|(x, p)| x - p).collect();
let given: Vec<Decimal> = self.given.iter().map(|g| g * sign).collect();
crate::kernel::apportion_cumulative(