Skip to content

Commit 867b66d

Browse files
committed
strconv: support negative decimals
1 parent 9029f39 commit 867b66d

File tree

2 files changed

+16
-17
lines changed

2 files changed

+16
-17
lines changed

strconv/decimal.go

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@ import (
88
func ParseDecimal(b []byte) (float64, int) {
99
// float64 has up to 17 significant decimal digits and an exponent in [-1022,1023]
1010
i := 0
11-
//sign := 1.0
12-
//if 0 < len(b) && b[0] == '-' {
13-
// sign = -1.0
14-
// i++
15-
//}
11+
sign := 1.0
12+
if 0 < len(b) && b[0] == '-' {
13+
sign = -1.0
14+
i++
15+
}
1616

1717
start := -1
1818
dot := -1
@@ -52,17 +52,16 @@ func ParseDecimal(b []byte) (float64, int) {
5252
exp++
5353
}
5454
if 1023 < exp {
55-
return math.Inf(1), i
56-
//if sign == 1.0 {
57-
// return math.Inf(1), i
58-
//} else {
59-
// return math.Inf(-1), i
60-
//}
55+
if sign == 1.0 {
56+
return math.Inf(1), i
57+
} else {
58+
return math.Inf(-1), i
59+
}
6160
} else if exp < -1022 {
6261
return 0.0, i
6362
}
6463

65-
f := float64(n) // sign * float64(n)
64+
f := sign * float64(n)
6665
if 0 <= exp && exp < 23 {
6766
return f * float64pow10[exp], i
6867
} else if 23 < exp && exp < 0 {

strconv/decimal_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ func TestParseDecimal(t *testing.T) {
1212
f string
1313
expected float64
1414
}{
15-
{"5", 5},
15+
{"5", 5.0},
1616
{"5.1", 5.1},
1717
{"0.0000000000000000000000000005", 5e-28},
1818
{"18446744073709551620", 18446744073709551620.0},
@@ -34,10 +34,10 @@ func TestParseDecimalError(t *testing.T) {
3434
n int
3535
expected float64
3636
}{
37-
{"+1", 0, 0},
38-
{"-1", 0, 0},
39-
{".", 0, 0},
40-
{"1e1", 1, 1},
37+
{"+1", 0, 0.0},
38+
{"-1", 2, -1.0},
39+
{".", 0, 0.0},
40+
{"1e1", 1, 1.0},
4141
}
4242
for _, tt := range tests {
4343
t.Run(fmt.Sprint(tt.f), func(t *testing.T) {

0 commit comments

Comments
 (0)