为什么在时间中添加一天会改变秒的小数部分?
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是浮点舍入问题。您的数字存储为双精度浮点数,精度为 53 位。 2^53 大约为 9*10^15,给出 15 到 16 位十进制数字,具体取决于要表示的确切数字。
您可能会注意到,这两个数字分别有 16 和 15 位小数。你只排在最后一位。事实上,确切的存储值不是这两个十进制数,而是仅以小数二进制精确表示的值。
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.
当我这样做时,它并不适合我:
我相信这只是浮点数常见的一个小问题,并且您发现了一个小的精度误差。
这远小于一秒,即一天的 0.0000001。鉴于一天只有 86,400 秒,这通常不是问题,尽管这是将日期存储为日期并对其进行 Ruby 日期算术的一个很好的理由。
It didn't for me when I did:
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.