Skip to content

Commit

Permalink
Add Float32 helper
Browse files Browse the repository at this point in the history
  • Loading branch information
sam-ke authored and vmihailenco committed Apr 10, 2019
1 parent 2f1ad94 commit 94ec556
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
30 changes: 30 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,25 @@ func (cmd *Cmd) Uint64() (uint64, error) {
}
}

func (cmd *Cmd) Float32() (float32, error) {
if cmd.err != nil {
return 0, cmd.err
}
switch val := cmd.val.(type) {
case int64:
return float32(val), nil
case string:
f, err := strconv.ParseFloat(val, 32)
if err != nil {
return 0, err
}
return float32(f), nil
default:
err := fmt.Errorf("redis: unexpected type=%T for Float32", val)
return 0, err
}
}

func (cmd *Cmd) Float64() (float64, error) {
if cmd.err != nil {
return 0, cmd.err
Expand Down Expand Up @@ -585,6 +604,17 @@ func (cmd *StringCmd) Uint64() (uint64, error) {
return strconv.ParseUint(cmd.Val(), 10, 64)
}

func (cmd *StringCmd) Float32() (float32, error) {
if cmd.err != nil {
return 0, cmd.err
}
f, err := strconv.ParseFloat(cmd.Val(), 32)
if err != nil {
return 0, err
}
return float32(f), nil
}

func (cmd *StringCmd) Float64() (float64, error) {
if cmd.err != nil {
return 0, cmd.err
Expand Down
10 changes: 10 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,14 @@ var _ = Describe("Cmd", func() {
Expect(f).To(Equal(float64(10)))
})

It("supports float32", func() {
f := float32(66.97)

err := client.Set("float_key", f, 0).Err()
Expect(err).NotTo(HaveOccurred())

val, err := client.Get("float_key").Float32()
Expect(err).NotTo(HaveOccurred())
Expect(val).To(Equal(f))
})
})

0 comments on commit 94ec556

Please sign in to comment.