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')
.
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
来源:https://stackoverflow.com/questions/2990408/how-can-i-round-to-a-certain-floating-point-precision