Skip to content

Commit

Permalink
Fix wrong return RoundUp/RoundDown because of value after rescaled is…
Browse files Browse the repository at this point in the history
… ignore (#202)
  • Loading branch information
lovung committed Jan 17, 2021
1 parent 2740f7f commit 99f4d74
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
10 changes: 10 additions & 0 deletions decimal.go
Expand Up @@ -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"
//
Expand All @@ -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)
}
Expand All @@ -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"
//
Expand All @@ -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)
}
Expand Down
4 changes: 4 additions & 0 deletions decimal_test.go
Expand Up @@ -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", ""},
Expand All @@ -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", ""},
Expand Down Expand Up @@ -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", ""},
Expand All @@ -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", ""},
Expand Down

0 comments on commit 99f4d74

Please sign in to comment.