How can I round to a specific floating point precision?

I think this is a simple question. I want to:

a = 1.154648126486416;

to become:

a = 1.154;

and not:

a = 1.15000000000;

How to do it without using format('bank').

+3
source share
3 answers

You can do it:

a = floor(a*1000)/1000;
+7
source

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

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

will show: "The result is 1.154." on the command line. Or write a line to a file, etc. Etc.

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

: 1.1540

, , , "" "".

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

: 1.1550

0
source

Source: https://habr.com/ru/post/1748855/


All Articles