From 4b40f225e91a009021bac2ae6fd04a3d90c58b12 Mon Sep 17 00:00:00 2001 From: mudhoney Date: Tue, 27 Sep 2022 04:14:56 -0400 Subject: [PATCH] Float32 loading problem (#23) * fix float32 field loading * tests for float32 field problem --- csv_files/float32.csv | 3 +++ load.go | 2 ++ load_test.go | 23 ++++++++++++++++++++++- 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 csv_files/float32.csv diff --git a/csv_files/float32.csv b/csv_files/float32.csv new file mode 100644 index 0000000..cf1e5bc --- /dev/null +++ b/csv_files/float32.csv @@ -0,0 +1,3 @@ +header1, header2 +line1, 1.2 +line2, 2.3 diff --git a/load.go b/load.go index 7f9d379..07be1a8 100644 --- a/load.go +++ b/load.go @@ -204,6 +204,8 @@ func storeValue(rawValue string, valRv reflect.Value) error { return fmt.Errorf("error parsing int '%v':\n ==> %v", rawValue, err) } valRv.SetInt(value) + case reflect.Float32: + fallthrough case reflect.Float64: value, err := strconv.ParseFloat(rawValue, 64) if err != nil && rawValue != "" { diff --git a/load_test.go b/load_test.go index 34fd994..b147e43 100644 --- a/load_test.go +++ b/load_test.go @@ -1,6 +1,8 @@ package csvtag -import "testing" +import ( + "testing" +) type test struct { Name string `csv:"header1"` @@ -19,6 +21,11 @@ type testBool struct { ABool bool `csv:"header2"` } +type testF32 struct { + Name string `csv:"header1"` + Num float32 `csv:"header2"` +} + // Check the values are correct func checkValues(tabT []test) bool { return false || @@ -34,6 +41,12 @@ func checkBoolValues(tabT []testBool) bool { tabT[2].Name != "line3" || tabT[2].ABool != false } +func checkFloat32Values(tabT []testF32) bool { + return false || + tabT[0].Name != "line1" || tabT[0].Num != 1.2 || + tabT[1].Name != "line2" || tabT[1].Num != 2.3 +} + func TestValideFile(t *testing.T) { tabT := []test{} err := LoadFromPath("csv_files/valid.csv", &tabT) @@ -50,6 +63,14 @@ func TestBool(t *testing.T) { } } +func TestF32(t *testing.T) { + tabT := []testF32{} + err := LoadFromPath("csv_files/float32.csv", &tabT) + if err != nil || checkFloat32Values(tabT) { + t.Fail() + } +} + func TestBadHeader(t *testing.T) { tabT := []test{} err := LoadFromPath("csv_files/badHeader.csv", &tabT)