R issue with rounding milliseconds

前端 未结 4 1230
孤街浪徒
孤街浪徒 2020-12-18 00:46

Given the following issue with rounding milliseconds under R. How do I get around it so that the times are correct?

> options(digits.secs=3)
> as.POSI         


        
4条回答
  •  -上瘾入骨i
    2020-12-18 01:32

    This is the same problem as Milliseconds puzzle when calling strptime in R.

    Your example:

    > x <- as.POSIXlt("13:29:56.061", format='%H:%M:%OS', tz='UTC')
    > print(as.numeric(x), digits=20)
    [1] 1339075796.0610001087
    

    is not representative of the problem. as.numeric(x) converts your POSIXlt object to POSIXct before converting to numeric, so you get different floating-point-precision rounding errors.

    That's not how print.POSIXlt (which calls format.POSIXlt) works. format.POSIXlt formats each element of the POSIXlt list construct individually, so you would need to look at:

    print(x$sec, digits=20)
    [1] 56.060999999999999943
    

    And that number is truncated at the third decimal place, so you see 56.060. You can see this by calling format directly:

    > format(x, "%H:%M:%OS6")
    [1] "13:29:56.060999"
    

提交回复
热议问题