From 0e73258876d64edf8066fbc7958adfa6f8bfe4fd Mon Sep 17 00:00:00 2001 From: Denis Bernard Date: Thu, 7 May 2020 12:57:03 +0200 Subject: [PATCH] Add rationale for DefaultDecimalPrec Also fix SetInt test to cope with the new value. --- decimal.go | 8 ++++++++ decimal_test.go | 8 ++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/decimal.go b/decimal.go index 669cfdb..912446d 100644 --- a/decimal.go +++ b/decimal.go @@ -6,6 +6,14 @@ import ( "math/big" ) +// DefaultDecimalPrec is the default minimum precision used when creating a new +// Decimal from any other type. An uint64 requires up to 20 digits, which +// amounts to 2 x 19-digits Words (64 bits) or 3 x 9-digits Words (32 bits). +// Forcing the precision to 20 digits would result in 18 or 7 unused digits. +// Using 34 instead gives a higher precision at no performance or memory cost +// and gives room for 2 to 4 extra digits of extra precision for internal +// computations at no performance or memory cost either. Also 34 digits matches +// the precision of IEEE-754 decimal128. const DefaultDecimalPrec = 34 type Decimal struct { diff --git a/decimal_test.go b/decimal_test.go index e09dcf3..8284923 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -64,11 +64,15 @@ func TestDecimal_SetInt(t *testing.T) { t.Run(strconv.Itoa(i), func(t *testing.T) { b, _ := new(big.Int).SetString(td.s, td.b) d := new(Decimal).SetMode(ToNearestEven).SetPrec(td.p).SetInt(b) + ep := td.pr + if td.p == 0 && ep < DefaultDecimalPrec { + ep = DefaultDecimalPrec + } if !reflect.DeepEqual(td.d, d.mant) { t.Fatalf("\nexpected mantissa %v\n got %v", td.d, d.mant) } - if td.pr != d.Prec() { - t.Fatalf("\nexpected precision %v\n got %v", td.pr, d.Prec()) + if ep != d.Prec() { + t.Fatalf("\nexpected precision %v\n got %v", ep, d.Prec()) } if td.e != d.exp { t.Fatalf("\nexpected exponent %v\n got %v", td.p, d.Prec())