mirror of
https://github.com/shopspring/decimal.git
synced 2024-11-22 20:40:48 +01:00
Remove insignificant digits during string parsing
This commit is contained in:
parent
5471f2c322
commit
4e5e2ed948
2 changed files with 33 additions and 2 deletions
|
@ -112,8 +112,10 @@ func NewFromString(value string) (Decimal, error) {
|
||||||
// an int
|
// an int
|
||||||
intString = value
|
intString = value
|
||||||
} else if len(parts) == 2 {
|
} else if len(parts) == 2 {
|
||||||
intString = parts[0] + parts[1]
|
// strip the insignificant digits for more accurate comparisons.
|
||||||
expInt := -len(parts[1])
|
decimalPart := strings.TrimRight(parts[1], "0")
|
||||||
|
intString = parts[0] + decimalPart
|
||||||
|
expInt := -len(decimalPart)
|
||||||
exp += int64(expInt)
|
exp += int64(expInt)
|
||||||
} else {
|
} else {
|
||||||
return Decimal{}, fmt.Errorf("can't convert %s to decimal: too many .s", value)
|
return Decimal{}, fmt.Errorf("can't convert %s to decimal: too many .s", value)
|
||||||
|
|
|
@ -5,6 +5,7 @@ import (
|
||||||
"encoding/xml"
|
"encoding/xml"
|
||||||
"math"
|
"math"
|
||||||
"math/big"
|
"math/big"
|
||||||
|
"reflect"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"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) {
|
func TestNewFromFloatWithExponent(t *testing.T) {
|
||||||
type Inp struct {
|
type Inp struct {
|
||||||
float float64
|
float float64
|
||||||
|
|
Loading…
Reference in a new issue