Skip to content

Commit

Permalink
Add new helper methods: BigInt, BigFloat (#171)
Browse files Browse the repository at this point in the history
* Add new helper methods: BigInt, BigFloat
* Add few tests cases showing loss of precision after casting
  • Loading branch information
mwoss authored Apr 19, 2020
1 parent f1c1aea commit 1884f45
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
16 changes: 16 additions & 0 deletions decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,22 @@ func (d Decimal) IntPart() int64 {
return scaledD.value.Int64()
}

// BigInt returns integer component of the decimal as a BigInt.
func (d Decimal) BigInt() *big.Int {
scaledD := d.rescale(0)
i := &big.Int{}
i.SetString(scaledD.String(), 10)
return i
}

// BigFloat returns decimal as BigFloat.
// Be aware that casting decimal to BigFloat might cause a loss of precision.
func (d Decimal) BigFloat() *big.Float {
f := &big.Float{}
f.SetString(d.String())
return f
}

// Rat returns a rational number representation of the decimal.
func (d Decimal) Rat() *big.Rat {
d.ensureInitialized()
Expand Down
53 changes: 53 additions & 0 deletions decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1724,6 +1724,59 @@ func TestIntPart(t *testing.T) {
}
}

func TestBigInt(t *testing.T) {
testCases := []struct {
Dec string
BigIntRep string
}{
{"0.0", "0"},
{"0.00000", "0"},
{"0.01", "0"},
{"12.1", "12"},
{"9999.999", "9999"},
{"-32768.01234", "-32768"},
{"-572372.0000000001", "-572372"},
}

for _, testCase := range testCases {
d, err := NewFromString(testCase.Dec)
if err != nil {
t.Fatal(err)
}
if d.BigInt().String() != testCase.BigIntRep {
t.Errorf("expect %s, got %s", testCase.BigIntRep, d.BigInt())
}
}
}

func TestBigFloat(t *testing.T) {
testCases := []struct {
Dec string
BigFloatRep string
}{
{"0.0", "0"},
{"0.00000", "0"},
{"0.01", "0.01"},
{"12.1", "12.1"},
{"9999.999", "9999.999"},
{"-32768.01234", "-32768.01234"},
{"-572372.0000000001", "-572372"},
{"512.012345123451234512345", "512.0123451"},
{"1.010101010101010101010101010101", "1.01010101"},
{"55555555.555555555555555555555", "55555555.56"},
}

for _, testCase := range testCases {
d, err := NewFromString(testCase.Dec)
if err != nil {
t.Fatal(err)
}
if d.BigFloat().String() != testCase.BigFloatRep {
t.Errorf("expect %s, got %s", testCase.BigFloatRep, d.BigFloat())
}
}
}

func TestDecimal_Min(t *testing.T) {
// the first element in the array is the expected answer, rest are inputs
testCases := [][]float64{
Expand Down

0 comments on commit 1884f45

Please sign in to comment.