how to show certain number of decimal digits

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

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!

回答1:

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 


回答2:

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



回答3:

Change the format.

format shortG 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!