1

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")?

1
  • 1
    R doesn't have numbers with infinite precision. Numbers with decimals are stored as floating point numbers. While R often stores more digits than it prints by default, you are limited in the precision you are able to track. Maybe you could better describe what you are trying to do or why you think you need such a number. Commented Nov 11, 2015 at 18:48

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.