littleworth
littleworth

Reputation: 5169

Convert character base scientific number into number and preserving the scientific notation in R

I have this value in character:

 val <- "1e-14105"

What I want to do is to convert them into numeric and preserve the scientific notation. So the result is simply 1e-14105 as number.

I tried this but failed:

> as.numeric(val)
[1] 0
> format(as.numeric(val), scientific=TRUE)
[1] "0e+00"

What's the right way to do it?

Upvotes: 4

Views: 1288

Answers (1)

Scransom
Scransom

Reputation: 3335

The problem is a floating point issue and the degree of accuracy to which R is working. It is converting 1e-14105 to numeric, it's just then approximating it to zero. See The R Inferno: Circle 1, Falling into the Floating Point Trap.

> as.numeric("1e-14105")
[1] 0
> class(as.numeric("1e-14105"))
[1] "numeric"
> 1e-14105
[1] 0

Upvotes: 4

Related Questions