Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add implementation of CoefficientInt64 method #244

Merged
merged 2 commits into from Sep 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 9 additions & 3 deletions decimal.go
Expand Up @@ -756,14 +756,20 @@ func (d Decimal) Exponent() int32 {
return d.exp
}

// Coefficient returns the coefficient of the decimal. It is scaled by 10^Exponent()
// Coefficient returns the coefficient of the decimal. It is scaled by 10^Exponent()
func (d Decimal) Coefficient() *big.Int {
d.ensureInitialized()
// we copy the coefficient so that mutating the result does not mutate the
// Decimal.
// we copy the coefficient so that mutating the result does not mutate the Decimal.
return big.NewInt(0).Set(d.value)
}

// CoefficientInt64 returns the coefficient of the decimal as int64. It is scaled by 10^Exponent()
// If coefficient cannot be represented in an int64, the result will be undefined.
func (d Decimal) CoefficientInt64() int64 {
d.ensureInitialized()
return d.value.Int64()
}

// IntPart returns the integer component of the decimal.
func (d Decimal) IntPart() int64 {
scaledD := d.rescale(0)
Expand Down
30 changes: 30 additions & 0 deletions decimal_test.go
Expand Up @@ -2643,6 +2643,36 @@ func TestDecimal_Coefficient(t *testing.T) {
}
}

func TestDecimal_CoefficientInt64(t *testing.T) {
type Inp struct {
Dec string
Coefficient int64
}

testCases := []Inp{
{"1", 1},
{"1.111", 1111},
{"1.000000", 1000000},
{"1.121215125511", 1121215125511},
{"100000000000000000", 100000000000000000},
{"9223372036854775807", 9223372036854775807},
{"10000000000000000000", -8446744073709551616}, // undefined value
}

// add negative cases
for _, tc := range testCases {
testCases = append(testCases, Inp{"-" + tc.Dec, -tc.Coefficient})
}

for _, tc := range testCases {
d := RequireFromString(tc.Dec)
coefficient := d.CoefficientInt64()
if coefficient != tc.Coefficient {
t.Errorf("expect coefficient %d, got %d, for decimal %s", tc.Coefficient, coefficient, tc.Dec)
}
}
}

func TestNullDecimal_Scan(t *testing.T) {
// test the Scan method that implements the
// sql.Scanner interface
Expand Down