[R] rounding down with as.integer

Mike Miller mbmiller+l at gmail.com
Thu Jan 1 00:24:57 CET 2015

This is probably a FAQ, and I don't really have a question about it, but I 
just ran across this in something I was working on:

> as.integer(1000*1.003)
[1] 1002

I didn't expect it, but maybe I should have.  I guess it's about the 
machine precision added to the fact that as.integer always rounds down:

> as.integer(1000*1.003 + 255 * .Machine$double.eps)
[1] 1002

> as.integer(1000*1.003 + 256 * .Machine$double.eps)
[1] 1003

This does it right...

> as.integer( round( 1000*1.003 ) )
[1] 1003

...but this seems to always give the same answer and it is a little faster 
in my application:

> as.integer( 1000*1.003 + .1 )
[1] 1003

FYI - I'm reading in a long vector of numbers from a text file with no 
more than three digits to the right of the decimal.  I'm converting them 
to integers and saving them in binary format.


More information about the R-help mailing list