Nazmul
Nazmul

Reputation: 1

Why as.integer() is returning incorrect value?

I am using the following expression in my R-script and getting an incorrect value. I was wondering whether it is a bug or I am doing something wrong. Any help will be appreciated.

as.integer(10.7275*1e7)

it is returning 107274999. I was expecting it to return 107275000. How can I fix that?

Upvotes: 0

Views: 243

Answers (2)

Mankind_2000
Mankind_2000

Reputation: 2208

Its a floating point issue. One quick fix would be to use double precision floating point for better accuracy:

as.double(10.7275*1e7)                       # alternatively as.numeric()

# [1] 107275000

Also refer to this floating point post to get more information and resolutions for floating point math as commented by @Wai Ha Lee

Upvotes: -1

morgan121
morgan121

Reputation: 2253

This is due to computer inaccuracy with decimals (as mentioned in comments by @Suren). You can get around it by:

as.integer(ceiling(10.7275*1e7))

Note:

ceiling(as.integer(10.7275*1e7)) 

will not work (it will return the value you are getting now).

Upvotes: 2

Related Questions