Add implementation of CoefficientInt64 method (#244)

* Add implementation of CoefficientInt64 method
This commit is contained in:
Mateusz Woś 2021-09-10 15:48:44 +02:00 committed by GitHub
parent 483a047db9
commit b11a7c46d7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 3 deletions

View file

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

View file

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