MidpointRounding
How a number is rounded to a whole one, or to a number of decimals.
Rounding is two different questions. The first is what happens to a value exactly
halfway between two neighbours — does 12.5 become 12 or 13? — and only a half is ever
affected; the first two members answer it. The other three are directions, applied to
every value that has a fraction at all: towards zero, downwards, upwards. The library has
two defaults, one for numbers and one for money, and both are set in CkSettings.
Members
| Member | Meaning |
|---|---|
ToEven |
A half goes to the even neighbour: 12.5 becomes 12, 13.5 becomes 14. Banker's rounding — over thousands of .5 values it rounds up as often as down, so a sum does not drift. The default for numbers (CkSettings::NumberRounding). |
AwayFromZero |
A half goes away from zero: 12.5 becomes 13, -12.5 becomes -13. The schoolbook rule, and the accounting one. The default for money (CkSettings::MoneyRounding). |
ToZero |
Every fraction is dropped: 12.9 becomes 12, -12.9 becomes -12. |
ToNegativeInfinity |
Every fraction rounds down: 12.9 becomes 12, -12.1 becomes -13. |
ToPositiveInfinity |
Every fraction rounds up: 12.1 becomes 13, -12.9 becomes -12. |
The enum is backed by an int — ToEven is 0, AwayFromZero 1, ToZero 2,
ToNegativeInfinity 3, ToPositiveInfinity 4 — so a choice can be stored and read back
with MidpointRounding::from().
Where it is used
CkNumber::Round takes a rounding parameter, whose
default is ToEven (CkSettings::NumberRounding) — the same rule the integer readers
TinyInt, SmallInt, MediumInt, Integer and BigInt apply when they round a
fraction to a whole number. CkMoney never asks: every amount it
rounds — in Round, Format, MinorUnits, ToMoney and the calculations — goes
AwayFromZero (CkSettings::MoneyRounding), so US$10.005 is always 10.01 on an invoice.
Quick look
use SafeCoder\CommonKit\CkNumber;
use SafeCoder\CommonKit\Enums\MidpointRounding;
CkNumber::Round(2.5); // -> 2.0 (ToEven is the default: a half to the even neighbour)
CkNumber::Round(3.5); // -> 4.0
CkNumber::Round(
input: 2.5,
rounding: MidpointRounding::AwayFromZero
); // -> 3.0
CkNumber::Round(
input: 12.9,
rounding: MidpointRounding::ToZero
); // -> 12.0
CkNumber::Round(
input: -12.1,
rounding: MidpointRounding::ToNegativeInfinity
); // -> -13.0
CkNumber::Round(
input: 12.1,
rounding: MidpointRounding::ToPositiveInfinity
); // -> 13.0