Skip to content

Commit

Permalink
Add support for RoundHalfEven aka "Banker's Rounding" (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
floodfx authored Dec 8, 2022
1 parent 28b0298 commit 1ecf001
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
4 changes: 4 additions & 0 deletions amount.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ const (
RoundUp
// RoundDown rounds towards 0, truncating extra digits.
RoundDown
// RoundHalfEven rounds up if the next digit is > 5. If the next digit is equal
// to 5, it rounds to the nearest even decimal. Also called bankers' rounding.
RoundHalfEven
)

// InvalidNumberError is returned when a numeric string can't be converted to a decimal.
Expand Down Expand Up @@ -401,6 +404,7 @@ func roundingContext(decimal *apd.Decimal, mode RoundingMode) *apd.Context {
RoundHalfDown: apd.RoundHalfDown,
RoundUp: apd.RoundUp,
RoundDown: apd.RoundDown,
RoundHalfEven: apd.RoundHalfEven,
}
ctx := *decimalContext(decimal)
ctx.Rounding = extModes[mode]
Expand Down
10 changes: 10 additions & 0 deletions amount_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -529,11 +529,21 @@ func TestAmount_RoundTo(t *testing.T) {
{"12.345", 2, currency.RoundDown, "12.34"},
{"12.347", 2, currency.RoundDown, "12.34"},

{"12.344", 2, currency.RoundHalfEven, "12.34"},
{"12.345", 2, currency.RoundHalfEven, "12.34"},
{"12.346", 2, currency.RoundHalfEven, "12.35"},

{"12.334", 2, currency.RoundHalfEven, "12.33"},
{"12.335", 2, currency.RoundHalfEven, "12.34"},
{"12.336", 2, currency.RoundHalfEven, "12.34"},

// Negative amounts.
{"-12.345", 2, currency.RoundHalfUp, "-12.35"},
{"-12.345", 2, currency.RoundHalfDown, "-12.34"},
{"-12.345", 2, currency.RoundUp, "-12.35"},
{"-12.345", 2, currency.RoundDown, "-12.34"},
{"-12.345", 2, currency.RoundHalfEven, "-12.34"},
{"-12.335", 2, currency.RoundHalfEven, "-12.34"},

// More digits that the amount has.
{"12.345", 4, currency.RoundHalfUp, "12.3450"},
Expand Down

0 comments on commit 1ecf001

Please sign in to comment.