Skip to content

Commit

Permalink
Merge pull request #22 from hurbcom/feature/add_parse_to_float
Browse files Browse the repository at this point in the history
add parse  to float
  • Loading branch information
luis fernando fontoura spaniol authored Feb 2, 2021
2 parents 4acb29d + 0b558d7 commit 1a78af6
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -508,3 +508,11 @@ func Fill(dest interface{}, src interface{}) {
}
}
}

// ParseStringToFloat64 parse the string to float64
func ParseStringToFloat64(s string) (float64, error) {
if s == "" || s == "0" {
return float64(0), nil
}
return strconv.ParseFloat(s, 64)
}
53 changes: 53 additions & 0 deletions lib/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -833,3 +833,56 @@ func TestFill(t *testing.T) {

assert.Equal(t, "Bobby", a.Name)
}

func TestParseStringToFloat64(t *testing.T) {
type args struct {
s string
}
tests := []struct {
name string
args args
want float64
wantErr bool
}{
{
name: "Should parse ok",
args: args{
s: "123.123",
},
want: 123.123,
},
{
name: "Should parse with zero value",
args: args{
s: "",
},
want: 0,
},
{
name: "should parse with zero",
args: args{
s: "0",
},
want: 0,
},
{
name: "Should return an error",
args: args{
s: "abc",
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ParseStringToFloat64(tt.args.s)
if (err != nil) != tt.wantErr {
t.Errorf("ParseStringTFloat64() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("ParseStringTFloat64() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 1a78af6

Please sign in to comment.