From 3c692774ac4c47c7a296ec96e553719dba1a68fc Mon Sep 17 00:00:00 2001 From: Matthew Lane Date: Fri, 28 Jul 2017 14:12:53 -0500 Subject: [PATCH] Added NewFromBigInt constructor & unit test (#56) --- decimal.go | 8 ++++++++ decimal_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/decimal.go b/decimal.go index c4467a9..9cdd494 100644 --- a/decimal.go +++ b/decimal.go @@ -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: diff --git a/decimal_test.go b/decimal_test.go index 358609d..983c800 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -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 {