How to have the exact same formatting of numbers in C++and R?
c++, formatting, r
Solution
Have you tried `sprintf` or `formatC`?
To be specific I think
sprintf("%e", 2.82e-01)
should do the trick but as mentioned above have a look at help(sprintf), which describes the various formatting capabilities of this function ...
Problem
I am writing a functional test in R for a program in C++. The typical output file has some columns as "string" and the other columns as "double". Then, I would like to use `diff` to compare the expected output file returned by R with the observed output file returned by C++. In pseudo-C++, I simply do this: ``` stringstream ssTxt; ssTxt.precision (7); ssTxt.setf (ios::scientific); for(i=0; i<10; ++i){ ssTxt << names[i] << " " << values[0][i] << " " << values[1][i] << " " << values[2][i] << endl; // write in file and clear ssTxt } ``` Here is a typical output: ``` item1 2.8200000e-01 500 4.1846912e-04 ``` In R, I do that: ``` results <- data.frame(name="item1", val1=0.282, val2=500, val3=0.00041846912873) write.table(x=format(results, digits=8, nsmall=7, scientific=TRUE), file=...) ``` Here is the output corresponding to the same data: ``` item1 2.82e-01 500 4.1846912e-04 ``` As you can see, it almost works, but R doesn't add trailing 0 after "2.82". I prefer to change the R code rather than the C++ code. So how can I do that?