1

This is a really stupid problem in R but I don't know how to fix it. I'm having the following code:

library(lubridate)
options(digits.secs = 3)

start <- strptime("2013-12-10 01:59:26.901", format = "%Y-%m-%d %H:%M:%OS", tz = "America/Chicago")
end <- strptime("2013-12-10 01:59:27.729", format = "%Y-%m-%d %H:%M:%OS", tz = "America/Chicago")

When I do end - start I expect the output to be 0.828 seconds but instead I get 0.8280001.

EDIT: I know why it happens now, but not how to fix it. How do I fix this?

Thank you!

Marjolein
  • 77
  • 7

1 Answers1

0

The way to fix it is to round the result to the precision you expect. This can be done by modifying the value, or just formatting the output. For example,

round(end - start, 3)

will print Time difference of 0.828 secs.

A difficulty with this approach is that you might not know the original precision of the values, e.g. if start and end came from a different program. There's really no good solution in that case.

Another possibility is to format the difference; then it will be printed the way you want, but not changed. For example,

format(end-start, digits = 3)

which produces 0.828 secs.

user2554330
  • 37,248
  • 4
  • 43
  • 90
  • Thank you so much for your help! My problem isn't really with the rounding of `end - start` but I need the timestamps to be correct. Eventually I want to filter my data with the timestamps, but the filtering gets the wrong result as something is not entirely correct in the timestamps. – Marjolein Nov 03 '21 at 13:14
  • If it's just for filtering, I would use the formatting approach. Don't test if the value is equal to `0.828`, test if the formatted value is equal to `"0.828"`. (Add `" secs"` or whatever if necessary.) – user2554330 Nov 03 '21 at 13:25