Fix wrong return RoundUp/RoundDown because of value after rescaled is ignore (#202)

This commit is contained in:
Vu Long (Drake) 2021-01-18 06:50:46 +07:00 committed by GitHub
parent 2740f7f782
commit 99f4d74cf2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 0 deletions

View file

@ -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)
}

View file

@ -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", ""},