Add Float32 helper

This commit is contained in:
sam-ke 2019-04-10 15:27:06 +03:00 committed by Vladimir Mihailenco
parent 2f1ad94a2a
commit 94ec556725
2 changed files with 40 additions and 0 deletions

View File

@ -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) { func (cmd *Cmd) Float64() (float64, error) {
if cmd.err != nil { if cmd.err != nil {
return 0, cmd.err return 0, cmd.err
@ -585,6 +604,17 @@ func (cmd *StringCmd) Uint64() (uint64, error) {
return strconv.ParseUint(cmd.Val(), 10, 64) 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) { func (cmd *StringCmd) Float64() (float64, error) {
if cmd.err != nil { if cmd.err != nil {
return 0, cmd.err return 0, cmd.err

View File

@ -57,4 +57,14 @@ var _ = Describe("Cmd", func() {
Expect(f).To(Equal(float64(10))) 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))
})
}) })