Rounding Numerical values in an array to decimal points

35 views (last 30 days)
How can i round the values in the array to 2 decimasl places. The round functio n does not work with arrays how would i be able to get to the Expected output below?
Code:
a = [12.75687 44.8947584 55.2382 6.34758485]
round =(a,2)
Expected Output:
[12.76 44.89 55.24 6.35]
  2 Comments
Stephen23
Stephen23 on 18 Oct 2021
Edited: Stephen23 on 18 Oct 2021
"The round functio n does not work with arrays"
It does (and always has):
a = [12.75687,44.8947584,55.2382,6.34758485]
a = 1×4
12.7569 44.8948 55.2382 6.3476
b = round(a,2)
b = 1×4
12.7600 44.8900 55.2400 6.3500
dpb
dpb on 18 Oct 2021
Perhaps OP is confusing the number of decimal places printed at the command line with the precision of the answer -- in
b = round(a,2)
b = 1×4
12.7600 44.8900 55.2400 6.3500
there are still four digits after the decimal displayed.
That is, of course, a fignewton of the format option selected in the command line and is not able to be changed other than for the relatively few available options -- "short", "long", ...
The one that might be of interest here for the specific case of two decimals is
>> a = [12.75687,44.8947584,55.2382,6.34758485];
b = round(a,2)
b =
12.7600 44.8900 55.2400 6.3500
>> format bank
>> b
b =
12.76 44.89 55.24 6.35
>>
But, it has the disadvantage for very large numbers that it is fixed format.
If it is needed to display a specific number of digits, one has to use one of the formatting options with fprintf or the like.

Sign in to comment.

Answers (1)

Leepakshi
Leepakshi on 6 Mar 2025
Hi Teoman,
To round numbers in a MATLAB array to two decimal places and ensure they are displayed correctly, you can use the round function and adjust the display format.
Please refer to the following example:
a = [12.75687, 44.8947584, 55.2382, 6.34758485];
rounded_a = round(a, 2);
format shortG; % This sets the display format or
% format bank % will also work
disp(rounded_a);
This code rounds each element of the array a to two decimal places and sets the display format to show fewer decimal places.
Refer to the following documentation on format function:
Please refer to below documentation which can help to get more alternatives using sprintf:
sprint can be used as:
txt = sprintf('Displaying pi: \n %f \n %.2f \n %12f', A);
Hope this helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!