Question

I have a question about the way R handles double, numeric and character data types internally.

My problem arises from this snippet of code:

dn <- 1.0
dc <- "1.0"
dn == dc  #  FALSE
dn  # 1
as.double(dc) # 1

The problem is I expected a double to retain the formatting, the digits after the comma, instead of being cut in such a brutal way which makes it difficult to compare it to a character version of the same number. Of course the problem is not present with numbers like, say 16.2, for which the formatting is correctly retained.

Is there a way to make the 'double' formatting lasting?

Thank you very much

Was it helpful?

Solution

dn <- 1.0
sprintf("%.1f",dn)
# [1] "1.0"
sprintf("%.2f",dn)
# [1] "1.00"
sprintf("%.22f",dn)
# [1] "1.0000000000000000000000"

dc == sprintf("%.1f",dn)
#[1] TRUE

dn is stored internally as double precision float ("numeric" in R). How you display it is up to you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top