Added NewFromBigInt constructor & unit test (#56)

This commit is contained in:
Matthew Lane 2017-07-28 14:12:53 -05:00 committed by Victor Quinn
parent 16a9418214
commit 3c692774ac
2 changed files with 41 additions and 0 deletions

View file

@ -81,6 +81,14 @@ func New(value int64, exp int32) Decimal {
}
}
// NewFromBigInt returns a new Decimal from a big.Int, value * 10 ^ exp
func NewFromBigInt(value *big.Int, exp int32) Decimal {
return Decimal{
value: big.NewInt(0).Set(value),
exp: exp,
}
}
// NewFromString returns a new Decimal from a string representation.
//
// Example:

View file

@ -231,6 +231,39 @@ func TestNewFromFloatWithExponent(t *testing.T) {
}
}
func TestNewFromBigIntWithExponent(t *testing.T) {
type Inp struct {
val *big.Int
exp int32
}
tests := map[Inp]string{
Inp{big.NewInt(123412345),-3}: "123412.345",
Inp{big.NewInt(2234), -1}: "223.4",
Inp{big.NewInt(323412345), 1}: "3234123450",
Inp{big.NewInt(423412345), 0}: "423412345",
Inp{big.NewInt(52341235), -5}: "523.41235",
Inp{big.NewInt(623412345),-6}: "623.412345",
Inp{big.NewInt(723412345),-7}: "72.3412345",
}
// add negatives
for p, s := range tests {
if p.val.Cmp(Zero.value) > 0 {
tests[Inp{p.val.Neg(p.val), p.exp}] = "-" + s
}
}
for input, s := range tests {
d := NewFromBigInt(input.val, input.exp)
if d.String() != s {
t.Errorf("expected %s, got %s (%s, %d)",
s, d.String(),
d.value.String(), d.exp)
}
}
}
func TestJSON(t *testing.T) {
for _, s := range testTable {
var doc struct {