user2763361
user2763361

Reputation: 3919

Casting numeric from character imprecision

as.numeric(as.character(1363821605424526000)) results in 1363821605424526080.

Why and how do I prevent this?

Upvotes: 2

Views: 108

Answers (1)

Simon O'Hanlon
Simon O'Hanlon

Reputation: 59970

One solution is to use the gmp library (GNU Multiple Precision library) to create and do basic arithmetic with big integers...

require(gmp)
as.bigz("1363821605424526000")
#Big Integer ('bigz') :
#[1] 1363821605424526000

Note the use of " round the number. This is to protect it from being parsed as a numeric data type by R which of course will not be able to represent this number exactly in the given data structures. " gets R to treat it as a character variable before as.bigz turns it into a big integer type.

Examples

as.bigz("1363821605424526000") + 1
#Big Integer ('bigz') :
#[1] 1363821605424526001

as.bigz("1363821605424526000")^3
#Big Integer ('bigz') :
#[1] 2536720967038413127881466345733319337545403576000000000

Upvotes: 3

Related Questions