How do you round up or down to a decimal

26 vues (au cours des 30 derniers jours)
Ted H
Ted H le 2 Jan 2023
Modifié(e) : Ted H le 3 Jan 2023
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.

Réponse acceptée

Image Analyst
Image Analyst le 2 Jan 2023
Modifié(e) : Image Analyst le 2 Jan 2023
To round up use ceil
To round down use floor
  2 commentaires
Ted H
Ted H le 3 Jan 2023
I don't see in ceil where you can handle the decimal. I see the time component only.
Voss
Voss le 3 Jan 2023
Modifié(e) : Voss le 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

Connectez-vous pour commenter.

Plus de réponses (1)

John D'Errico
John D'Errico le 2 Jan 2023
Modifié(e) : John D'Errico le 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 commentaires
John D'Errico
John D'Errico le 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 le 3 Jan 2023
Modifié(e) : Ted H le 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by