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

131 次查看(过去 30 天)
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!

请先登录,再进行评论。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by