From 4e5e2ed9487b5591a148c917ff79cc4c6fb56a14 Mon Sep 17 00:00:00 2001 From: Jason Biegel Date: Tue, 7 Feb 2017 12:33:26 -0500 Subject: [PATCH] Remove insignificant digits during string parsing --- decimal.go | 6 ++++-- decimal_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/decimal.go b/decimal.go index 3942b3d..045badb 100644 --- a/decimal.go +++ b/decimal.go @@ -112,8 +112,10 @@ func NewFromString(value string) (Decimal, error) { // an int intString = value } else if len(parts) == 2 { - intString = parts[0] + parts[1] - expInt := -len(parts[1]) + // strip the insignificant digits for more accurate comparisons. + decimalPart := strings.TrimRight(parts[1], "0") + intString = parts[0] + decimalPart + expInt := -len(decimalPart) exp += int64(expInt) } else { return Decimal{}, fmt.Errorf("can't convert %s to decimal: too many .s", value) diff --git a/decimal_test.go b/decimal_test.go index 718943a..60dc6fa 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -5,6 +5,7 @@ import ( "encoding/xml" "math" "math/big" + "reflect" "sort" "strconv" "strings" @@ -156,6 +157,34 @@ func TestNewFromStringErrs(t *testing.T) { } } +func TestNewFromStringDeepEquals(t *testing.T) { + type StrCmp struct { + str1 string + str2 string + expected bool + } + tests := []StrCmp{ + StrCmp{"1", "1", true}, + StrCmp{"10", "10.0", true}, + StrCmp{"1.1", "1.10", true}, + StrCmp{"1.001", "1.01", false}, + } + + for _, cmp := range tests { + d1, err1 := NewFromString(cmp.str1) + d2, err2 := NewFromString(cmp.str2) + + if err1 != nil || err2 != nil { + t.Errorf("error parsing strings to decimals") + } + + if reflect.DeepEqual(d1, d2) != cmp.expected { + t.Errorf("comparison result is different from expected results for %s and %s", + cmp.str1, cmp.str2) + } + } +} + func TestNewFromFloatWithExponent(t *testing.T) { type Inp struct { float float64