Question

pry(main)> time = Time.now
=> 2012-01-20 00:10:44 +0000
pry(main)> (time + 4.days).to_f
=> 1327363844.9709609
pry(main)> time.to_f
=> 1327018244.970961
Was it helpful?

Solution

It didn't for me when I did:

a = Time.now.to_f  
=> 1327018729.22437  
b = (a + 4.days).to_f  
=> 1327364329.22437  

I believe this is just a small round issue common with floats and you found a small precision error.

That is much less than a second, i.e. .0000001 of a day. Given there are only 86,400 seconds in a day this is frequently not a issue, although a good reason to store dates as dates and do Ruby date arithmetic on them.

OTHER TIPS

This is a floating point rounding issue. Your number is stored as a double precision floating point number which has a precision of 53 bits. 2^53 is roughly 9*10^15 giving you between 15 and 16 decimal digits, depending on the exact number to be represented.

You may notice that these two numbers have 16 and 15 decimal digits respectively. You are off only in the last place. In truth the exact stored value is neither of these two decimal numbers but rather something that is only exactly represented in fractional binary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top