Is there a way to floor to a specified number of digits?
128 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
John D'Errico
on 24 May 2017
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 Comment
More Answers (1)
Arthur Vieira
on 22 Sep 2021
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 Comments
Christopher Stokes
on 18 May 2023
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
on 19 Jul 2023
Thank you as well, this function helped me figure the niche issue I was trying to solve!
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!