How can I round to a certain floating-point precision?

不想你离开。 提交于 2019-12-05 22:28:37

You could do this:

a = floor(a*1000)/1000;

Building on @gnovice's answer, you can format the output as a string to get rid of the extra zeros. See the sprintf documentation for all the formatting options.

str=sprintf('The result is %1.3f.',a);
disp(str)

will show "The result is 1.154." in the command prompt. Or write the string to file, etc., etc.

a = 1.154648126486416;
% desired precision 
b = -3;
% your answer
ans = floor(a*10^(-b))/(10^(-b));

The answer is 1.1540

this is good if you don't care about the rest of digits but if you do care then you just have to simply change "floor" to "round".

ans = round(a*10^(-b))/(10^(-b));

The answer is 1.1550

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