MATLAB: Find the number of digits after the decimal point in a number, please help!

decimal pointfloating point

Say you have a number, x, and you want to find the number of digits after the decimal point. I know that in matlab, one way to do it would be to convert the number to a string and find the length from after the decimal point, but I think num2str has issues. How would you find the number of digits after the decimal point in a number then (the question is complicated by the fact that the numbers are floating point).
%
function y = decimalpoint(x)
x = abs(x); %in case of negative numbers
y = 0;
while (floor(x)~=x)
y = y+1;
x = x*10;
end
This code doesn't work for some cases, such as decimalpoint(11.111). How would I make the code work for all cases? I think recursion could be useful too, but probably not necessary.

Best Answer

x=11.111
x = abs(x); %in case of negative numbers
n=0
while (floor(x*10^n)~=x*10^n)
n=n+1
end