Round to specified decimal number?

29 ビュー (過去 30 日間)
Keith Lewis
Keith Lewis 2016 年 11 月 15 日
コメント済み: Keith Lewis 2016 年 11 月 15 日
How can I round a number to the nearest specified decimal value?
For instance round 3.7234234 to the nearest 0.25 multiple, so it would output 3.75.
  1 件のコメント
Keith Lewis
Keith Lewis 2016 年 11 月 15 日
Here is a solution based on Daniels link. Just added a test for whether to round up or down based on which is closer.
prompt={'Decimal to be rounded:','Decimal interval to round to'};
defaultans={'2.149','0.05'};
num_lines=1;
answer=inputdlg(prompt,dlg_title,num_lines,defaultans);
deimcalToRound=str2double(answer{1});
roundingInterval=str2double(answer{2});
up = roundingInterval*ceil(deimcalToRound/roundingInterval);
down = roundingInterval*floor(deimcalToRound/roundingInterval);
subup = deimcalToRound - up
subdown = deimcalToRound - down
asubup = abs(subup)
asubdown = abs(subdown)
if asubdown < asubup
roundingInterval*floor(deimcalToRound/roundingInterval)
else
roundingInterval*ceil(deimcalToRound/roundingInterval)
end

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

採用された回答

Daniel kiracofe
Daniel kiracofe 2016 年 11 月 15 日
  1 件のコメント
Keith Lewis
Keith Lewis 2016 年 11 月 15 日
Thanks!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by