mirror of https://github.com/go-redis/redis.git
Merge pull request #1009 from go-redis/fix/float32-helper
Add Float32 helper
This commit is contained in:
commit
292bdd8230
30
command.go
30
command.go
|
@ -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
|
||||
|
@ -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
|
||||
|
|
|
@ -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))
|
||||
})
|
||||
})
|
||||
|
|
Loading…
Reference in New Issue