user2543622
user2543622

Reputation: 6786

Converting character to numeric without losing information

I would like to convert below character data to a numeric data. But as.numeric is trimming some information. How can I ensure that I get 1.00000000000000000000000000000001 after converting to numeric?

> a="1.00000000000000000000000000000001"
> as.numeric(a)
[1] 1
> as.numeric(a,10)
[1] 1
> as.numeric(as.character(a))
[1] 1
> as.double(a)
[1] 1

Upvotes: 2

Views: 1067

Answers (2)

Carl Witthoft
Carl Witthoft

Reputation: 21532

If you need to carry that much precision, consider the package Rmpfr

library(Rmpfr)
longa<-mpfr("1.00000000000000000000000000000001",200)
longa
1 'mpfr' number of precision  200   bits 
[1] 1.0000000000000000000000000000000100000000000000000000000000004

Notice that even here there's a little 4x10-[bignumber] error.

Try something fancier:

mpfr("1.00000000000000000000000000000001e50",200)
1 'mpfr' number of precision  200   bits 
[1] 100000000000000000000000000000001000000000000000000 #is an integer, so no error
mpfr("1.00000000000000000000000000000001e50",200)/1e50
1 'mpfr' number of precision  200   bits 
[1] 0.99999999999999992370230158908114578838913309406505827306768701

What I'm pointing out is that you need to be really careful when working with floating-point numbers on computers.

Upvotes: 3

cafefeed
cafefeed

Reputation: 21

It is not a problem with as.character but with the limits of the numerical precision:

> a <- 1.00000000000000000000000000000001
> a == 1
[1] TRUE

Upvotes: 2

Related Questions