user3624032
user3624032

Reputation: 89

R conversion between numeric and string

So the following code generates the following output:

> as.character(10^-14)

"0.00000000000001"

However this alternative code generates this alternative output:

> as.character(123123 + 10^-14)

"123123"

My question, is there a way to force R to preserve the added precision when doing the addition (i.e. I want the output of "123123.00000000000001")?

Upvotes: 1

Views: 76

Answers (1)

jtatria
jtatria

Reputation: 526

Don't use as.character(x) and use sprintf(f,x) instead, as it allows you to specify an arbitrary format for the resulting strings.

for your specific example:

sprintf( "%.14f", 123123 + 10^-14 )

However, do note that sprintf only takes care of the formatting of the string representation, and it has no control over loss of information upon conversion from floating point values: in the line above, the 1 digit on the 14th decimal place gets lost if the magnitude of the input number is too large (compare the output of 1 + 10^-14 vs. 123123 + 10^-14), but this happens before any formatting by sprintf (and also affects as.character, as you have already seen).

Upvotes: 1

Related Questions