Is there a way to floor to a specified number of digits?

131 ビュー (過去 30 日間)
Fwelin
Fwelin 2017 年 5 月 24 日
コメント済み: Marcus Palozzi 2023 年 7 月 19 日
I want to floor a series of numbers, but I want to do it to a specified number of digits (for example, I want to round both 12351231 and 12752309 to 12000000). Neither round nor floor work for this purpose.
Is there a function I'm not aware of, or a simple combination of functions that can do this operation? I'm only working with integers, so decimal compatibility is unnecessary, if that matters.

採用された回答

John D'Errico
John D'Errico 2017 年 5 月 24 日
Sort of.
Multiply by a power of 10. Use floor. Then divide by that power of 10.
HOWEVER, don't expect it to work perfectly.
x = 1.23;
floor(x*10)/10
ans =
1.2
It looks like it worked perfectly. But did it?
sprintf('%0.55f',ans)
ans =
'1.1999999999999999555910790149937383830547332763671875000'
Nope. It did not work. In fact, the result is just slightly less than 1.2. This is because 1.2 is not truly representable as a double precision number.
So be careful. If the 1.2 that came about is what you wanted, then you are done.
  1 件のコメント
Niklas Kurz
Niklas Kurz 2023 年 1 月 10 日
I always admire your answeres and your keen insight!

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

その他の回答 (1 件)

Arthur Vieira
Arthur Vieira 2021 年 9 月 22 日
I think I've understood the question as I'm looking for the same thing.
Matlab has the function
round(val, nS, 'significant')
Where val is the value you wish to round, and nS is the number of significant digits to round to.
What we would like is similar option for floor() and ceil(), but is not supported (I'm using R2020a). So I wrote this function that should do the trick:
% Solution:
function flooredVal = floorS(val, nS)
pw = ceil(log10(val)); % Find order of magnitude of val.
res = 10^(pw-nS); % Resolution to round to.
flooredVal = floor(val/res)*res; % < change floor() to ceil(), for ceiling equivalent.
end
To make ceilS() just change floor() to ceil() in the last line of the function.
Usage examples:
g.floorS(12752309, 2)
ans =
12000000
g.floorS(12.752309, 2)
ans =
12
g.floorS(0.0012752309, 2)
ans =
0.0012
  2 件のコメント
Christopher Stokes
Christopher Stokes 2023 年 5 月 18 日
Thanks! This is a nice little function that I've needed on a few occasions. One tweak that allows it to work with negative values is to use the absolute value when getting the order of magnitude in the first line of the code:
pw = ceil(log10(abs(val)));
Marcus Palozzi
Marcus Palozzi 2023 年 7 月 19 日
Thank you as well, this function helped me figure the niche issue I was trying to solve!

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

カテゴリ

Help Center および File ExchangeCorrelation and Convolution についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by