如何显示一定数量的小数位数 [英] how to show certain number of decimal digits

查看:47
本文介绍了如何显示一定数量的小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Matlab中,如何控制在命令窗口中显示的小数位数?

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

例如

>> x = 0.4654

>> x=0.4654

x =

0.4654

如何在命令窗口中将变量x的值分别显示为0.5、0.47和0.465?

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

谢谢!

推荐答案

我认为不存在对任意位置进行舍入的内置方法,但是您可以通过执行round(x * 10 ^ number的地方)/10 ^ 地方的数目.这会打印出带有尾随的零,如果您想摆脱那些零,则必须执行某种特殊格式的打印,例如sprintf,以便在某种情况下可以通过以下操作获得所需的结果:

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)

希望对您有帮助!

如果您想对矩阵进行处理,我不确定是否有更好的方法,但是您可以循环遍历以x为矩阵的行:

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

这篇关于如何显示一定数量的小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆