Ivan
Ivan

Reputation: 153

MATLAB: Convert string to number and then back to string

There is a string containing a number in an arbitrary format (e.g., 12, -34.5, and 6.78e-9). The goal is to convert this string into the corresponding number and then convert this number back to a string such that (a) the precision given in the original string is preserved, and (b) the resulting string has an adequate format (probably, the most adequate format is the format of the original string). I thought the problem could be easily solved using str2num and num2str; however, in some cases, MATLAB seems to be mangling the final result as shown below:

    >> a = '1e23'

    a =

    1e23

    >> b = str2num(a)

    b =

       1.0000e+23

    >> c = num2str(b)

    c =

    9.999999999999999e+22

One solution is to use a general format string:

    >> c = num2str(b, '%e')

    c =

    1.000000e+23

However, in this case, the output looks rather cumbersome for numbers of small orders:

    >> d = num2str(1, '%e')

    d =

    1.000000e+00

In most cases, num2str without additional parameters does a pretty good job resulting in a nicely formatted string. The question is: Is there a way to eliminate the 9.999999999999999e+22 problem?

Thank you!

Regards, Ivan

Upvotes: 1

Views: 485

Answers (1)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

In general the representation of one input string does not contain enough information to determine the format. Hence (assuming you want to output slightly different numbers and cannot simply store the number in string format), the simplest way would be to try and find a format that you like.

Judging from your comments, I think you will be happy with:

format short g

For large numbers it will give:

x = num2str(1.0000e+23);str2num(x)

ans =

        1e+23

And for small numbers:

 x = num2str(1);str2num(x)

ans =

     1

Upvotes: 2

Related Questions