How to manually adjust the decimal point?

2 views (last 30 days)
I used (5*rand) to generate the random numbers in the range 0 to 5 and got the answers like 4.5693, 3.4211 etc. The default format long and short only can display 5 digits and 15 digits. How to have 7 digits to get the answers like 4.569312, 3.421178 etc? Please help.

Accepted Answer

Wayne King
Wayne King on 25 Sep 2012
Edited: Wayne King on 25 Sep 2012
x = 5*rand;
fprintf('%1.6f\n',x)
Or if you want to keep it as a string:
y = sprintf('%1.6f\n',x);
Note now: y
gives you what you want, but if you convert it back to a number with
str2num(y)
the formatting will change back.

More Answers (1)

Daniel Shub
Daniel Shub on 25 Sep 2012
You could also overload display for class double and format short to make it display 7 digits instead of 15. Since double is the default class in MATLAB it seems a little bit buggier to me than when I suggested overloading display for char. Basically create a folder @double and add it to the MATLAB path. inside that folder add the following function called display.m.
function display(x)
if strcmpi(get(0, 'Format'), 'Short')
name = inputname(1);
if isempty(name)
name = 'ans';
end
builtin('disp', sprintf('%s =\n%20.7f\n', name, x));
else
builtin('display', x);
end
end

Products

Community Treasure Hunt

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

Start Hunting!