Academia
Academia

Reputation: 4124

Converting string to num with a specific format in Matlab

>> str = '0009.51998'
>> str2num(str)

or

>> sscanf(str,'%f')

ans = 9.5200

I want to get this instead:

ans = 9.51998

Upvotes: 0

Views: 1477

Answers (1)

Andrew Janke
Andrew Janke

Reputation: 23858

You are getting that. It's just being rounded off to four decimal places when it's displayed. Do format long to see more precision.

>> str = '0009.51998';
>> x = sscanf(str, '%f')
x =
    9.5200
>> format long
>> x
x =
   9.519980000000000
>> 

You can also use str2double as an alternative to sscanf. It's safer and more flexible than str2num. That is because str2num uses the eval command. For example, try the following:

  str2num(' figure();imshow(''peppers.png'')')

You might be surprised at the results.

Upvotes: 3

Related Questions