Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -1182,7 +1182,13 @@ func (c *Context) quantize(d, v *Decimal, exp int32) Condition {
p := int32(d.NumDigits()) - diff
if p < 0 {
if !d.IsZero() {
var discard Decimal
discard.Coeff.Set(&d.Coeff)
discard.Exponent = -diff
d.Coeff.SetInt64(0)
if c.Rounding.ShouldAddOne(&d.Coeff, d.Negative, discard.Cmp(decimalHalf)) {
d.Coeff.SetInt64(1)
}
res = Inexact | Rounded
}
} else {
Expand Down
35 changes: 35 additions & 0 deletions decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,41 @@ func TestQuantize(t *testing.T) {
}
}

func TestQuantizeRounding(t *testing.T) {
tests := []struct {
s string
e int32
rnd Rounder
expect string
}{
{s: "0.002", e: -1, rnd: RoundCeiling, expect: "0.1"},
{s: "1.002", e: -1, rnd: RoundCeiling, expect: "1.1"},
{s: "-0.002", e: -1, rnd: RoundCeiling, expect: "-0.0"},
{s: "0.002", e: -1, rnd: RoundFloor, expect: "0.0"},
{s: "-0.002", e: -1, rnd: RoundFloor, expect: "-0.1"},
{s: "0.002", e: -1, rnd: RoundUp, expect: "0.1"},
{s: "0.002", e: -1, rnd: RoundDown, expect: "0.0"},
{s: "0.04", e: -1, rnd: RoundHalfUp, expect: "0.0"},
{s: "0.05", e: -1, rnd: RoundHalfUp, expect: "0.1"},
{s: "0.05", e: -1, rnd: RoundHalfEven, expect: "0.0"},
}
for _, tc := range tests {
t.Run(fmt.Sprintf("%s: %d %s", tc.s, tc.e, tc.rnd), func(t *testing.T) {
c := Context{Precision: 100, Rounding: tc.rnd, MaxExponent: 1000, MinExponent: -1000, Traps: DefaultTraps}
d, _, err := NewFromString(tc.s)
if err != nil {
t.Fatal(err)
}
if _, err := c.Quantize(d, d, tc.e); err != nil {
t.Fatal(err)
}
if s := d.String(); s != tc.expect {
t.Fatalf("expected: %s, got: %s", tc.expect, s)
}
})
}
}

func TestCmpOrder(t *testing.T) {
tests := []struct {
s string
Expand Down