필터 지우기
필터 지우기

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

조회 수: 122 (최근 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개)

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 CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by