0

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

Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73
Luigi Tiburzi
  • 4,265
  • 7
  • 32
  • 43
  • 2
    are you asking about the formatting when outputting numerics? if so, see `?format`. Or are you asking about machine precision? In which case you want `all.equal(as.numeric(dc) ,dn)` – Ricardo Saporta Jan 27 '14 at 15:17
  • ORLY? What's the difference between `16.2` and `16.20000` ? But more to the point, there's no such thing as "the character version" of a number. – Carl Witthoft Jan 27 '14 at 15:30
  • both `sprintf("%.1f", dn) == dc` and `dn == as.double(dc)` are TRUE. You cannot expect to compare a number with a string and hope this will evaluate to TRUE. – Carlos Cinelli Jan 27 '14 at 15:41
  • @carloscinelli I expected it to be TRUE simply because 16.2 == "16.2" --> TRUE and so it seemed to me obvious the TRUE in this case too. It seems like R applies an automatic casting to a simpler type before the comparison – Luigi Tiburzi Jan 29 '14 at 15:01
  • @carlwitthoft if you compare a double and a character there is indeed a difference between 16.2 and 16.20000 if you have a precise format to respect. The character version of a number is simply the string representing the number – Luigi Tiburzi Jan 29 '14 at 15:02
  • You are missing the point. You can create any character string you want to "look like" the representation of a number. It's still not the number, and the printed representation of a stored `double` is just another character string. There is no valid way to compare a numerical value with a char string. – Carl Witthoft Jan 29 '14 at 15:07

1 Answers1

1
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.

jlhoward
  • 58,004
  • 7
  • 97
  • 140
  • Ok, my problem was only "1.0" == 1.0 --> FALSE because it seemed like he did an internal conversion casting the double to an integer – Luigi Tiburzi Jan 29 '14 at 14:56