read 2 digits in a txt file using %f
Show older comments
I use

to create 1000 2 digits random number in a txt file, which looks like below.

now I want to read the file for 2 digits by using %.2f, at below there are two code, the difference is one is using %f and read 4 digits which add 2 zero at the end, the another one using %.2f and got nothing.


I dont understand why it happend like that.
And for further calculation I want only 2 digits accuracy, is there any settings like globle setting to define I only want 0.xx rather than 0.xxxx?
1 Comment
"I dont understand why it happend like that."
Because you are confusing how numeric data are stored in computer memory with how they are displayed on your screen. The precision of the numbers stored in memory is fixed. You can changed the FORMAT, but this only changes how they are displayed, not how they are stored.
"And for further calculation I want only 2 digits accuracy, is there any settings like globle setting to define I only want 0.xx rather than 0.xxxx?"
There is no (common) numeric data type that stores any formatting information (e.g. the number of trailing digits to display), so what you are are requesting simply does not correspond to the reality of how numeric computing works.
Accepted Answer
More Answers (1)
Scott MacKenzie
on 15 Jul 2021
Edited: Scott MacKenzie
on 15 Jul 2021
0 votes
If you examine the documentation for fscanf, it states that the correct formatSpec to use when reading floating-point numbers is %f. There is no provision for using a more detailed formatSpec as commonly done when writing data using fprintf.
As for your follow-up question, the internal storage of the data is what it is -- full precision floating point. This is completely separate from how numbers are displayed. If you want to display only 2-decimal places that's a different issue. This would be controlled in the usual way; i.e., using the desired formatSpec, such as %.2f, in fprintf.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!