diff options
author | Matthew Lane <mlane@connamara.com> | 2017-07-29 03:12:53 +0800 |
---|---|---|
committer | Victor Quinn <mail@victorquinn.com> | 2017-07-29 03:12:53 +0800 |
commit | 3c692774ac4c47c7a296ec96e553719dba1a68fc (patch) | |
tree | 00bfbc78040ff45c089fa3c3d5c087e5373392dd | |
parent | 16a941821474ee3986fdbeab535a68a8aa5a85d2 (diff) | |
download | dexon-decimal-3c692774ac4c47c7a296ec96e553719dba1a68fc.tar.gz dexon-decimal-3c692774ac4c47c7a296ec96e553719dba1a68fc.tar.zst dexon-decimal-3c692774ac4c47c7a296ec96e553719dba1a68fc.zip |
Added NewFromBigInt constructor & unit test (#56)
-rw-r--r-- | decimal.go | 8 | ||||
-rw-r--r-- | decimal_test.go | 33 |
2 files changed, 41 insertions, 0 deletions
@@ -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 { |