Skip to content

Commit

Permalink
Fix field floating point parsing misrepresentation
Browse files Browse the repository at this point in the history
This commit fixes an issue where fields with floating points
that have zero prefixes and underscores are being parsed as
numbers.

Now those are treated as string values.

See #736
  • Loading branch information
tidwall committed May 4, 2024
1 parent 20522ef commit 51e6862
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
10 changes: 7 additions & 3 deletions internal/field/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,13 @@ func ValueOf(data string) Value {
} else if math.IsNaN(num) {
return Value{kind: Number, data: "NaN", num: nan}
}
return Value{kind: Number, data: data, num: num}
}
if gjson.Valid(data) {
// Make sure that this is a JSON compatible number.
// For example, "000123" and "000_123" both parse as floats but aren't
// really Numbers that can be represents in JSON.
if gjson.Valid(data) {
return Value{kind: Number, data: data, num: num}
}
} else if gjson.Valid(data) {
data = strings.TrimSpace(data)
r := gjson.Parse(data)
switch r.Type {
Expand Down
3 changes: 2 additions & 1 deletion internal/field/field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,5 +130,6 @@ func TestWeight(t *testing.T) {
}

func TestNumber(t *testing.T) {
assert.Assert(ValueOf("012").Num() == 12)
assert.Assert(ValueOf("12").Num() == 12)
assert.Assert(ValueOf("012").Num() == 0)
}
2 changes: 1 addition & 1 deletion internal/field/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func TestList(t *testing.T) {
})
assert.Assert(names == "fellohellojellonello")
assert.Assert(datas == "123456789012")
assert.Assert(nums == 1380)
assert.Assert(nums == 1368)

names = ""
datas = ""
Expand Down

0 comments on commit 51e6862

Please sign in to comment.