how to show certain number of decimal digits
In Matlab, how to control the number of decimal digits for 开发者_JS百科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!
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
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
Change the format.
format shortG
精彩评论