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?

11 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 (2)

Manikanta Aditya
Manikanta Aditya on 22 Mar 2024
% Long format for pi
format long
pi_long = pi
pi_long =
3.141592653589793
disp(['Long format: ', num2str(pi_long)])
Long format: 3.1416
% Short format for other values
format short
val_short = 1.1
val_short = 1.1000
disp(['Short format: ', num2str(val_short)])
Short format: 1.1
Thanks
  2 Comments
Manikanta Aditya
Manikanta Aditya on 22 Mar 2024
I thought when combined with num2str() might do the job but looks like as it converts the number into a string using the current format which might not reflect the long or short format I've set. Thanks for bringing it up.

Sign in to comment.


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.

Products

Community Treasure Hunt

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

Start Hunting!