Clear Filters
Clear Filters

How do you round up or down to a decimal

59 views (last 30 days)
I want to round UP to a specific decimal location (tenths in my current need).
I am getting errors using round():
a = 6.234;
b = round( a, 1);
gives 6.2. It works, but is not UP. It rounded DOWN. So I add TieBreaker:
b = round( a, 1, TieBreaker="plusinf");
gives
Error using round
Too many input arguments.
I missed something
b = round( a, TieBreaker="plusinf");
gives
Error using round
Third input must be either 'decimals' or 'significant'.
I missed something
Any comments, corrections, alternate methods are appreciated.

Accepted Answer

Image Analyst
Image Analyst on 2 Jan 2023
Edited: Image Analyst on 2 Jan 2023
To round up use ceil
To round down use floor
  2 Comments
Ted H
Ted H on 3 Jan 2023
I don't see in ceil where you can handle the decimal. I see the time component only.
Voss
Voss on 3 Jan 2023
Edited: Voss on 3 Jan 2023
You can do this kind of thing:
a = 6.234;
% round UP to the tenths:
b = ceil(a*10)/10
b = 6.3000
a = 6.237;
% round DOWN to the hundredths:
b = floor(a*100)/100
b = 6.2300

Sign in to comment.

More Answers (1)

John D'Errico
John D'Errico on 2 Jan 2023
Edited: John D'Errico on 2 Jan 2023
You are trying to use capabilities of round that are not present in your (older) MATLAB release.
For that code to work, you need to upgrade to a current release. But a simple call to round should still work for you.
b = round(6.234,1)
b = 6.2000
c = round(6.253,1)
c = 6.3000
Just that the option you are trying to use is a more recent capability.
  3 Comments
John D'Errico
John D'Errico on 2 Jan 2023
I am constantly being surprised, since I too often forget to read the release notes for every release.
Ted H
Ted H on 3 Jan 2023
Edited: Ted H on 3 Jan 2023
Rereading the matlab documentation, tiebreaker is only for the exact midpoint. So there is no round up or round down. This does not solve my problem. @Image Analyst solution does work, however a minor complaint is that it reduces readability (IMO).
Unrelated to the technique, I would have thought rounding up or down to a specific decimal place was a need, but I suppose not, or it was resolved by users dividing and multiplying. Matlab was first commercialized in the 80s, and not until 2014 was this need made a function, while this is standard in many other programs.
@John D'Errico your solution is just rounding. not rounding always up or always down to a specific decimal place. I might not have made this as clear as I should have. I edited the original post.

Sign in to comment.

Tags

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!