How to convert a Lua string to float

Viewed 32067

I am writing a simple Lua script to calculate a median from a Sorted Set (http://redis.io/commands/#sorted_set) within Redis 2.8. The script is below

local cnt = redis.call("ZCARD", KEYS[1])

if cnt > 0 then
        if cnt%2 > 0 then
                local mid = math.floor(cnt/2)
                return redis.call("ZRANGE", KEYS[1], mid, mid)
        else
                local mid = math.floor(cnt/2)
                local vals = redis.call("ZRANGE", KEYS[1], mid-1, mid)
                return (tonumber(vals[1]) + tonumber(vals[2]))/2.0
        end
else
        return nil
end

The problem is the script always returns an integer, when the result should be a float. The result is wrong.

$ redis-cli zrange floats 0 100
1) "1.1"
2) "2.1"
3) "3.1"
4) "3.4975"
5) "42.63"
6) "4.1"

$ redis-cli EVAL "$(cat median.lua)" 1 floats
(integer) 3

The correct result should be (3.1 + 3.4975)/2.0 == 3.298

2 Answers

sorry i have no explanation of this i encounter this by accidental when making script

function int2float(integer)
  return integer + 0.0
end
Related