7
$\begingroup$

I am trying to convert a string which contains a decimal number into a number with out any lost of precision. For example the string 5000000.0000000009 should become the number 5000000.0000000009 and not 5000000.000000001 Using the built in function like ToExpression certain numbers are rounded to machine precision but not all.

For example:

FullForm@ToExpression @ "5000000.0000000009" 

Outputs:

5.000000000000001`*^6 

Note: ToExpression returns the correct result for other slightly different numbers.

FullForm@ToExpression @ "5000000.00000000099" 

Outputs:

5.00000000000000099`17.69897000433602*^6 

Why does ToExpression round some numbers and not others or am I misunderstanding the output?

$\endgroup$

1 Answer 1

5
$\begingroup$

Basically, ToExpression converts number strings to machine precision if it can. Your example is an edge case where ToExpression converts the number to machine precision, but the machine real is not able to store all of the digits. One workaround is to indicate the precision explicitly:

ToExpression["5000000.0000000009`17"]//InputForm 

5.0000000000000009`17.*^6

Note that converting the above extended precision number into a machine number yields the result that you were getting before:

N @ ToExpression["5000000.0000000009`17"] //InputForm 

5.000000000000001*^6

Your other examples where things work as expected are because ToExpression is forced to convert to an extended precision number, or ToExpression converts to a machine number that is capable of representing all of the digits.

$\endgroup$
2
  • 1
    $\begingroup$ This it would seem would require the user then to edit all the input strings (may be they are in files) and add the correct `nn values to each string? Is this correct? $\endgroup$ Commented Aug 30, 2017 at 18:14
  • $\begingroup$ My actual solution is to split the decimals on the periods and then use FromDigits to build a fraction, but I was interested in why it happens. $\endgroup$ Commented Aug 30, 2017 at 19:36

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.