From bc70c3beb98b8ca44b8e5de7bb185f6963b03a50 Mon Sep 17 00:00:00 2001 From: Mathieu Post Date: Fri, 29 Nov 2019 06:17:06 +0100 Subject: [PATCH] Add NewFromInt and NewFromInt32 (#72) Add NewFromInt and NewFromInt32 --- README.md | 2 +- decimal.go | 26 +++++++++++++++++++++++++ decimal_test.go | 50 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 54c1a6b..912d68d 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ func main() { panic(err) } - quantity := decimal.NewFromFloat(3) + quantity := decimal.NewFromInt(3) fee, _ := decimal.NewFromString(".035") taxRate, _ := decimal.NewFromString(".08875") diff --git a/decimal.go b/decimal.go index a29ef04..d6612d4 100644 --- a/decimal.go +++ b/decimal.go @@ -87,6 +87,32 @@ func New(value int64, exp int32) Decimal { } } +// NewFromInt converts a int64 to Decimal. +// +// Example: +// +// NewFromInt(123).String() // output: "123" +// NewFromInt(-10).String() // output: "-10" +func NewFromInt(value int64) Decimal { + return Decimal{ + value: big.NewInt(value), + exp: 0, + } +} + +// NewFromInt32 converts a int32 to Decimal. +// +// Example: +// +// NewFromInt(123).String() // output: "123" +// NewFromInt(-10).String() // output: "-10" +func NewFromInt32(value int32) Decimal { + return Decimal{ + value: big.NewInt(int64(value)), + exp: 0, + } +} + // NewFromBigInt returns a new Decimal from a big.Int, value * 10 ^ exp func NewFromBigInt(value *big.Int, exp int32) Decimal { return Decimal{ diff --git a/decimal_test.go b/decimal_test.go index 395357f..be32f99 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -477,6 +477,56 @@ func TestNewFromFloatWithExponent(t *testing.T) { } } +func TestNewFromInt(t *testing.T) { + tests := map[int64]string{ + 0: "0", + 1: "1", + 323412345: "323412345", + 9223372036854775807: "9223372036854775807", + } + + // add negatives + for p, s := range tests { + if p > 0 { + tests[-p] = "-" + s + } + } + + for input, s := range tests { + d := NewFromInt(input) + if d.String() != s { + t.Errorf("expected %s, got %s (%s, %d)", + s, d.String(), + d.value.String(), d.exp) + } + } +} + +func TestNewFromInt32(t *testing.T) { + tests := map[int32]string{ + 0: "0", + 1: "1", + 323412345: "323412345", + 2147483647: "2147483647", + } + + // add negatives + for p, s := range tests { + if p > 0 { + tests[-p] = "-" + s + } + } + + for input, s := range tests { + d := NewFromInt32(input) + if d.String() != s { + t.Errorf("expected %s, got %s (%s, %d)", + s, d.String(), + d.value.String(), d.exp) + } + } +} + func TestNewFromBigIntWithExponent(t *testing.T) { type Inp struct { val *big.Int