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

▼魔方 西西 提交于 2020-01-23 11:23:44

问题


I think it's a simple question. I want:

a = 1.154648126486416;

to become:

a = 1.154;

and not:

a = 1.15000000000;

How do I do that without using format('bank').


回答1:


You could do this:

a = floor(a*1000)/1000;



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/2990408/how-can-i-round-to-a-certain-floating-point-precision

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