Tim
Tim

Reputation: 99556

how to show certain number of decimal digits

In Matlab, how to control the number of decimal digits for displaying in command window?

For example,

>> x=0.4654

x =

0.4654

how to display the value of the variable x as 0.5, 0.47, 0.465 respectively in command window?

Thanks!

Upvotes: 3

Views: 38818

Answers (3)

Muhammad Ali Awan
Muhammad Ali Awan

Reputation: 1

Change the format.

format shortG

Upvotes: 0

Ameer
Ameer

Reputation: 2638

I don't think there is built in rounding to arbitrary places, but you can achieve the rounded result by doing round(x*10^number of places)/10^number of places. This prints out with the trailing zeroes, if you want to get rid of those you have to do a specially formatted print like sprintf to the degrees so in your case you could get the results you want by doing:

sprintf('%.1f', round(x*10)/10)
sprintf('%.2f', round(x*100)/100)
sprintf('%.3f', round(x*1000)/1000)

I hope that helps!

Edit: If you want to do it for matrices, I'm not sure if there's a better way but you could just loop over the rows given x as a matrix:

for i=1:length(x(:,1)),
disp(sprintf('%.2f\t', round(x(i,:)*100)/100))
end

Upvotes: 4

Geodesic
Geodesic

Reputation: 893

You have control over the command window using the format command. I suggest you take a look at doc format, which gives you specific options.

If you need more precision, you'd be better off using disp, and / or a rounding function such as: z = round(x/y)*y

Upvotes: 2

Related Questions