Loren on the Art of MATLAB

September 3rd, 2009

Rounding Results

There are frequent questions on the MATLAB newsgroup about rounding results to a certain number of decimal places. MATLAB itself doesn't provide this functionality explicitly, though it is easy to accomplish.

Contents

Sidetrack : A Little MathWorks History

MathWorks' first Massachusetts office phone number was 653-1415 (ignoring country and area codes). The astute reader will notice that the last 5 digits are an approximation for (or, in MATLAB, pi). A local resident called one day to say that she kept getting calls for MathWorks and she wasn't sure why. But it was quite inconvenient for her because she spent lots of time on the second floor of her home, and the phone was on the first floor. The excess round-trips were taxing her! To understand what was happening, you should know that in some of the early MathWorks materials, the phone number was listed as .

Example

format long
x = 1.23456789
x =
   1.234567890000000

Use round. Here we get no decimals at all.

round(x)
ans =
     1

There are many ways to get the number of decimals you want. Here's one way to round to 3 decimals.

round(x*1000)/1000
ans =
   1.235000000000000

Here's another way.

sprintf('%0.3f',x)
ans =
1.235

And another. In this case, using the "easy" way to specify the format, you need to know how many integral digits there are as well.

str2num(num2str(x,4))
ans =
   1.235000000000000

Tools for Rounding Solutions

There are a lot of tools for helping you round numbers. The functions I list here for MATLAB form the basis of many, if not all, of the specific solutions.

MATLAB

Mapping Toolbox

File Exchange Rounding Tools

% N= num2str(X,SF);
% N= str2num(N);

Question for You

When you round values, do you want this for display only, or wanted for calculations? Some applications I can think of might include processing data that has a smaller number of bits of precision to start with. What applications do you need rounding for in your calculations? Post here with your thoughts.


Get the MATLAB code

Published with MATLAB® 7.8

11 Responses to “Rounding Results”

  1. Ness replied on :

    Dear Loren,

    I have used the first option you mention several times, and it’s been always for the post-processing part and never for the calculations.

    Greets

  2. Cris Luengo replied on :

    I’ve used things like ceil(x/1000)*1000 to calculate axis limits for pretty graphs. I think it’s nice when there’s a label at the top end of the axis, especially with logarithmic scaling.

  3. Ben replied on :

    Counting derangements:

    dn = round(factorial(n)/exp(1))
    
  4. Daniel replied on :

    For display I allways use the *printf() version.
    For calculations, the first method proposed is the only one I find reasonable, even if it doesn’t exactly give the most readable code.
    Sometimes I use a method not presented here, and that is the typecast method. Of course, it only makes sense when you want to round to the classical number formats, but you are absolutely sure you get what you want.

  5. Tim Davis replied on :

    [65 pi], that’s a fun round-about story. Her phone number was 653-1416, correctly rounded, wasn’t it? Her round trips were rounded up.

    If you need a few more digits (4,493 of them) just look at my T-shirt :-)

    http://www.thinkgeek.com/tshirts-apparel/unisex/sciencemath/6e7e/

    But the best round is another one. Cheers!

  6. Ben replied on :
    >> floor(22*(15/22))
    ans =
        14
    
    >> floor(49*(1/49))
    ans =
         0
    
  7. Loren replied on :

    Ben-

    Obviously you still need to be aware of numerical round-off in the calculations done before rounding in the first place. And using floor instead of round may not be what you want to do.

    –Loren

  8. Craig Miller replied on :

    Loren,
    I use rounding for calculations and comparisions with specification limits. For example if the lower spec limit is 1.8 and the calculated value is 1.78254343 I want this value to pass because it rounds to 1.8 which is not less than the specification limit. This may not be ‘correct’ but it’s the way we’ve done our spec checking since time immemorial (in computer terms anyway).
    Craig

  9. Loren replied on :

    Craig-

    I’m glad rounding works for you. Are you rounding to tenths for your work? Is your target value always in in tenths? Another possibility is to check if the calculated value is within a certain distance from the spec (e.g., abs(spec-calc) < SomeTolerance).

    –Loren

  10. OysterEngineer replied on :

    The illustrates why MatLab needs a smarter round function, much like even lowly Excel has, where the user can specify the number of digits to which you want to round to.

  11. Loren replied on :

    OysterEngineer-

    I recommend you use the support link on the right to enter your suggestion for round. Suggestions directly from customers tend to carry more weight. Thanks.

    –Loren

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


Loren Shure works on design of the MATLAB language at The MathWorks. She writes here about once a week on MATLAB programming and related topics.

  • Jun: I totally can not believe it, Loren. You are really helpful. Thank you so much, MATLAB master!
  • Loren: Wow folks- Always lots of interest when there’s a quickie to try out! I will only make 2 general...
  • Loren: Jun- ismember is your friend here: >> [aa,ind] = ismember(Array2,Arra y1) aa = 1 1 1 1 1 1 1 ind = 1 2 1 4 4 3...
  • Dan: I like the first way better than the second way. Combining the arrays into one and running any is nice, although...
  • James Myatt: How about I = (a == 0 | b == 0); a(I) = []; b(I) = [];
  • Tunc: Hello Loren, love your blog because of such inspiring and challenging comments to such ’small’...
  • Pekka Kumpulainen: Here is my tradeoff. I usually want to keep the original variables as they are most probably...
  • Iain: Followup: Of course, to allow NaNs (counting them as non-zero): mask = (a~=0) & (b~=0); The mask says “a...
  • Matt Fig: I would usually go with something like this: y = a&b; x = a(y); y = b(y); But I was surprised to find...
  • kk: c=all([a;b]) a(c) a(b)

These postings are the author's and don't necessarily represent the opinions of The MathWorks.