How do you round up or down to a decimal

241 ビュー (過去 30 日間)
Ted H
Ted H 2023 年 1 月 2 日
編集済み: Ted H 2023 年 1 月 3 日
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.

採用された回答

Image Analyst
Image Analyst 2023 年 1 月 2 日
編集済み: Image Analyst 2023 年 1 月 2 日
To round up use ceil
To round down use floor
  2 件のコメント
Ted H
Ted H 2023 年 1 月 3 日
I don't see in ceil where you can handle the decimal. I see the time component only.
Voss
Voss 2023 年 1 月 3 日
編集済み: Voss 2023 年 1 月 3 日
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

サインインしてコメントする。

その他の回答 (1 件)

John D'Errico
John D'Errico 2023 年 1 月 2 日
編集済み: John D'Errico 2023 年 1 月 2 日
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 件のコメント
John D'Errico
John D'Errico 2023 年 1 月 2 日
I am constantly being surprised, since I too often forget to read the release notes for every release.
Ted H
Ted H 2023 年 1 月 3 日
編集済み: Ted H 2023 年 1 月 3 日
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeDirection of Arrival Estimation についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by