Clear Filters
Clear Filters

Read 1.0 as 1.0 with fscanf(fid, '%f').

8 views (last 30 days)
SHC
SHC on 13 Jun 2023
Edited: SHC on 14 Jun 2023
When I read numbers from a text file using fscanf(fid, '%f'), MATLAB always returns the numbers as intergers if the numbers are ending with .0 (like 1.0 to 1) when format shortG is used.
They are same values, but I need the numbers as they are in the file for some reason.
Below is the content of test.txt as an example:
"1.0 2.1 3.0"
And if I run this MATLAB code:
format short G
fid = fopen('test.txt', 'r');
result = fscanf(fid, '%f')
The result is
result =
1
2.1
3
  2 Comments
Dyuman Joshi
Dyuman Joshi on 13 Jun 2023
Please attach the text file and your code. Use the paperclip button to do so.
Stephen23
Stephen23 on 13 Jun 2023
"but I need the numbers as they are in the file for some reason."
No numeric class stores formatting information.
You are confusing how numeric data are displayed with what data are actually stored in memory. Not the same things at all.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 13 Jun 2023

This is not possible in MATLAB. "format short g" instructs matlab to use specific output rules for display that are not compatible with your goals.

Note that it is only display that is affected. %f format reads as double precision. The values are double precision in storage. The "format" command chooses between rules for how different data types are to be displayed

You should probably be controlling the display exactly how you want it by using fprintf or compose()

  1 Comment
Walter Roberson
Walter Roberson on 13 Jun 2023
%create file
S = "1.0 2.1 3.0";
filename = fullfile(tempdir, "test.txt");
fid = fopen(filename, 'w');
fprintf(fid, "%s\n", S);
fclose(fid)
ans = 0
%crosscheck
dbtype(filename)
1 1.0 2.1 3.0
%read data
format short G
fid = fopen(filename, 'r');
result = fscanf(fid, '%f')
result = 3×1
1 2.1 3
class(result)
ans = 'double'
class(result(1))
ans = 'double'
format short eng
result
result = 3×1
1.0000e+000 2.1000e+000 3.0000e+000
Observe that the class() of result(1) is double, not one of the integer classes. Observe that if you change the format then how the data displays changes.
num2hex(result)
ans = 3×16 char array
'3ff0000000000000' '4000cccccccccccd' '4008000000000000'
If you care to look up the details of the representation of IEEE 754 Double Precision floating point numbers, you will see that the 3ff followed by all zeros is the exact floating point representation of 1.0

Sign in to comment.

More Answers (1)

SHC
SHC on 14 Jun 2023
Edited: SHC on 14 Jun 2023
Because what I wanted was a string not the number, so I used sprintf to get the desired result.
format short G
fid = fopen('test.txt', 'r');
result = fscanf(fid, '%f');
fclose(fid)
result(1)
a = sprintf('%.1f', result(1))
a =
'1.0'

Tags

Products


Release

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!