6

I'm interested to know why as.character(5.0) returns 5 but as.character(5.1) returns 5.1 in R. I tried to get an answer by reading the documentation but had no luck.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
user260474
  • 79
  • 4
  • 3
    R cannot distinguish between 5 and 5.0. Interally they are stored as exactly the same number so there is no reason to think that 5.0 would give anything different than 5. – G. Grothendieck Oct 21 '19 at 19:07
  • 1
    Run `identical(5.0, 5)` to see that `5` and `5.0` are identical objects. Both are stored as doubles. – slava-kohut Oct 21 '19 at 19:15
  • This is closely related to [R FAQ 7.31](https://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f) and https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal. That is, floating-point operations in any language (not just R) can produce seemingly counter-intuitive results when it comes to issues like equality, set membership, and presentation on R's console (where what you see is an approximation of what is actually in the object). – r2evans Oct 21 '19 at 19:27

2 Answers2

1

For more precise formatting of numbers as characters, you might use format:

> format(5,nsmall = 1)
[1] "5.0"
joran
  • 169,992
  • 32
  • 429
  • 468
1

I'm interested to know why as.character(5.0) returns 5

The key word here is "returns." What do you mean by that? Note that typing this in the console gives you 5:

> 5.0
[1] 5

5 is the same things as 5.0 for the purposes of calculation. So what you probably really care about is how 5 is printed. You thus need to use joran's method or a function like sprintf.

eable
  • 23
  • 5