Is it possible to use format long in one line of code and then use format short in another line of code on the same script?

7 views (last 30 days)
Bascially I am required to write pi in long format in the beginning of my script but later on I need to write values like 1.1 or 1.3, and I would like to do this part in short format. Is there any way to achve this?
  2 Comments
Stephen23
Stephen23 on 22 Mar 2024
"Is there any way to achve this? "
Sure, as other have shown you can fiddle around with the FORMAT. But a cleaner and more generalized approach would be to forget about the command windows settings: just use FPRINTF and specify the format explicitly.

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 22 Mar 2024
Just call format whenever you want to set the format and it will be that format for the rest of the script (or until you call format again)
format short g
pi
ans =
3.1416
format long g
pi
ans =
3.14159265358979
format short g
1.1
ans =
1.1
1.3
ans =
1.3
format long g
1.1
ans =
1.1
1.3
ans =
1.3
% Use sprintf to display with specified field width, for example 5, 3, or 23:
fprintf('%.5f', pi)
3.14159
fprintf('%.3f', 1.1)
1.100
fprintf('%.23f', 1.3)
1.30000000000000004440892
Note: format does not have any effect on fprintf. The number of decimal places shown when you use fprintf is the number after the percent symbol and dot.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!