0

R version 3.2.0 (2015-04-16), OS Ubuntu 14.04 Recently I have encountered a very strange problem which is really annoying.

Code:

q[94]
# [1] -0.7
paste0(q[94],".dat")
# [1] "-0.699999999999999.dat"
paste0(-0.7,".dat")
# [1] "-0.7.dat"

The paste0 function just change -0.7 to -0.699999999999999. This problem does not only happen at q[94] but also with the other elements in variable q(not all of them). But I can not figure out any patterns in this problem. And in this case the decimals digits change is not random at different trail. The -0.7 will always be changed to -0.699999999999999. And I have suspected that the problem is related to the options("digits"=), but I have tried to change this option, without any help. Another thing is this problem also happens at my server on which I am using Cent Os 4.5 with R version 3.1.3 (2015-03-09).

Update: I have tried paste0(as.character(q[94]),".dat"), but it's not work. Even I use as.character(q) to convert the entire vector to character vector, this problem also happens.

Edit for clarify: The answers in this question Why are these numbers not equal? have given good explanations about the the floating point number. What I want to do here is just convert the numeric number to a character string as what I see without any unexpected results. So if I use paste0() function what I should do?

Update: The best solution is use sprintf() function to control the digits of floating point number

Community
  • 1
  • 1
lovelyzlf
  • 107
  • 1
  • 11

0 Answers0