Skip to content

Commit

Permalink
Add implementation of CoefficientInt64 method (#244)
Browse files Browse the repository at this point in the history
* Add implementation of CoefficientInt64 method
  • Loading branch information
mwoss committed Sep 10, 2021
1 parent 483a047 commit b11a7c4
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
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

0 comments on commit b11a7c4

Please sign in to comment.