diff --git a/decimal.go b/decimal.go index 22f49e58..475161dc 100644 --- a/decimal.go +++ b/decimal.go @@ -897,6 +897,7 @@ func (d Decimal) Round(places int32) Decimal { // Example: // // NewFromFloat(545).RoundUp(-2).String() // output: "600" +// NewFromFloat(500).RoundUp(-2).String() // output: "500" // NewFromFloat(1.1001).RoundUp(2).String() // output: "1.11" // NewFromFloat(-1.454).RoundUp(1).String() // output: "-1.4" // @@ -906,6 +907,10 @@ func (d Decimal) RoundUp(places int32) Decimal { } rescaled := d.rescale(-places) + if d.Equal(rescaled) { + return d + } + if d.value.Sign() > 0 { rescaled.value.Add(rescaled.value, oneInt) } @@ -918,6 +923,7 @@ func (d Decimal) RoundUp(places int32) Decimal { // Example: // // NewFromFloat(545).RoundDown(-2).String() // output: "500" +// NewFromFloat(-500).RoundDown(-2).String() // output: "-500" // NewFromFloat(1.1001).RoundDown(2).String() // output: "1.1" // NewFromFloat(-1.454).RoundDown(1).String() // output: "-1.5" // @@ -927,6 +933,10 @@ func (d Decimal) RoundDown(places int32) Decimal { } rescaled := d.rescale(-places) + if d.Equal(rescaled) { + return d + } + if d.value.Sign() < 0 { rescaled.value.Sub(rescaled.value, oneInt) } diff --git a/decimal_test.go b/decimal_test.go index 7d4a38f1..72750abb 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -1022,6 +1022,7 @@ func TestDecimal_RoundUpAndStringFixed(t *testing.T) { {"5", 1, "5", "5.0"}, {"5", 0, "5", ""}, {"500", 2, "500", "500.00"}, + {"500", -2, "500", ""}, {"545", -1, "550", ""}, {"545", -2, "600", ""}, {"545", -3, "1000", ""}, @@ -1046,6 +1047,7 @@ func TestDecimal_RoundUpAndStringFixed(t *testing.T) { {"-5", 1, "-5", "-5.0"}, {"-5", 0, "-5", ""}, {"-500", 2, "-500", "-500.00"}, + {"-500", -2, "-500", ""}, {"-545", -1, "-540", ""}, {"-545", -2, "-500", ""}, {"-545", -3, "0", ""}, @@ -1111,6 +1113,7 @@ func TestDecimal_RoundDownAndStringFixed(t *testing.T) { {"5", 1, "5", "5.0"}, {"5", 0, "5", ""}, {"500", 2, "500", "500.00"}, + {"500", -2, "500", ""}, {"545", -1, "540", ""}, {"545", -2, "500", ""}, {"545", -3, "0", ""}, @@ -1135,6 +1138,7 @@ func TestDecimal_RoundDownAndStringFixed(t *testing.T) { {"-5", 1, "-5", "-5.0"}, {"-5", 0, "-5", ""}, {"-500", 2, "-500", "-500.00"}, + {"-500", -2, "-500", ""}, {"-545", -1, "-550", ""}, {"-545", -2, "-600", ""}, {"-545", -3, "-1000", ""},