Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rounding Modes

Keystone supports 7 rounding modes for precise control over decimal rounding.

Available Modes

ModeDescription2.5 →3.5 →-2.5 →
HalfEvenBanker’s rounding (ties to even)24-2
HalfUpTies round away from zero34-3
HalfDownTies round toward zero23-2
UpAlways round toward +∞34-2
DownAlways round toward -∞23-3
TowardZeroTruncate (round toward zero)23-2
AwayFromZeroRound away from zero34-3

Usage

#![allow(unused)]
fn main() {
use precision_core::{Decimal, RoundingMode};

let value = Decimal::new(12345, 3);  // 12.345

// Round to 2 decimal places
value.round(2, RoundingMode::HalfEven);   // 12.34
value.round(2, RoundingMode::HalfUp);     // 12.35
value.round(2, RoundingMode::Down);       // 12.34
value.round(2, RoundingMode::Up);         // 12.35

// Convenience methods
value.round_dp(2);  // 12.34 (uses HalfEven)
value.trunc(2);     // 12.34 (uses TowardZero)
value.floor();      // 12 (round toward -∞)
value.ceil();       // 13 (round toward +∞)
}

Banker’s Rounding (HalfEven)

The default mode. Ties round to the nearest even digit. This minimizes cumulative rounding error over many operations.

#![allow(unused)]
fn main() {
let a = Decimal::new(25, 1);  // 2.5
let b = Decimal::new(35, 1);  // 3.5

a.round(0, RoundingMode::HalfEven);  // 2 (rounds to even)
b.round(0, RoundingMode::HalfEven);  // 4 (rounds to even)
}

Financial Applications

Use CaseRecommended Mode
Invoice totalsHalfUp
Tax calculationsHalfUp or Up (toward government)
Interest accumulationHalfEven
Currency displayHalfUp
Truncation (e.g., satoshis)TowardZero

WASM

import { round } from '@dijkstra-keystone/wasm';

round("2.345", 2, "half_even");  // "2.34"
round("2.345", 2, "half_up");    // "2.35"
round("2.345", 2, "truncate");   // "2.34"

Available mode strings: "down", "up", "toward_zero", "truncate", "away_from_zero", "half_even", "bankers", "half_up", "half_down".