Lau
Lau

Reputation: 580

Time in nanoseconds in lua script for Redis

I am running a lua script in redis something like below:

eval "return tostring(tonumber(ARGV[1]))" 0 1538409827183989630

which should return 1538409827183989630 but is returning this 1.538409827184e+18 which is dropping last few nano second digits(Its a timestamp in nano seconds)

What is the correct way to do this assuming i need nano seconds precision cause i am comparing timestamps..

Upvotes: 0

Views: 1232

Answers (1)

Piglet
Piglet

Reputation: 28994

Lua numbers have two subtypes, integer and float which Lua chooses automatically.

One of the few if not the only situation where you have to care about that difference is when you want to convert a number to a string.

print(1538409827183989630) will print 1538409827183989630

print(1538409827183989630.0) will print as 1.538409827184e+18

If you want to make sure you get the same output you'll have to explicitly format the string.

local int = 1538409827183989630
local float = 1538409827183989630.0

print(string.format("%d", int))
print(string.format("%d", float))

output:

1538409827183989630
1538409827183989504

You'll notice that there will be a difference between both numbers due to the float -> integer conversion.

Upvotes: 0

Related Questions