From 80ec940054103d79e4d5b1be4b35bcbc7cd9af3c Mon Sep 17 00:00:00 2001 From: Egor Seredin <4819888+agmt@users.noreply.github.com> Date: Mon, 8 Apr 2024 23:38:20 +0900 Subject: [PATCH] Add NewFromUint64 constructor (#352) --- decimal.go | 12 ++++++++++++ decimal_test.go | 37 +++++++++++++++++++++++++++++-------- 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/decimal.go b/decimal.go index 2cf6bc0..5a404c8 100644 --- a/decimal.go +++ b/decimal.go @@ -130,6 +130,18 @@ func NewFromInt32(value int32) Decimal { } } +// NewFromUint64 converts an uint64 to Decimal. +// +// Example: +// +// NewFromUint64(123).String() // output: "123" +func NewFromUint64(value uint64) Decimal { + return Decimal{ + value: new(big.Int).SetUint64(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 0905ce8..60993e0 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -476,10 +476,11 @@ func TestNewFromFloatWithExponent(t *testing.T) { func TestNewFromInt(t *testing.T) { tests := map[int64]string{ - 0: "0", - 1: "1", - 323412345: "323412345", - 9223372036854775807: "9223372036854775807", + 0: "0", + 1: "1", + 323412345: "323412345", + 9223372036854775807: "9223372036854775807", + -9223372036854775808: "-9223372036854775808", } // add negatives @@ -501,10 +502,11 @@ func TestNewFromInt(t *testing.T) { func TestNewFromInt32(t *testing.T) { tests := map[int32]string{ - 0: "0", - 1: "1", - 323412345: "323412345", - 2147483647: "2147483647", + 0: "0", + 1: "1", + 323412345: "323412345", + 2147483647: "2147483647", + -2147483648: "-2147483648", } // add negatives @@ -524,6 +526,25 @@ func TestNewFromInt32(t *testing.T) { } } +func TestNewFromUint64(t *testing.T) { + tests := map[uint64]string{ + 0: "0", + 1: "1", + 323412345: "323412345", + 9223372036854775807: "9223372036854775807", + 18446744073709551615: "18446744073709551615", + } + + for input, s := range tests { + d := NewFromUint64(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