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

16 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 2 de Nov. de 2012
Editada: Azzi Abdelmalek el 2 de Nov. de 2012
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
  8 comentarios
Azzi Abdelmalek
Azzi Abdelmalek el 2 de Nov. de 2012
Editada: Azzi Abdelmalek el 2 de Nov. de 2012
x=11.111*(1-eps)
x*10^4=1.1111e+05
floor(x*10^4)=111109
and
x*10^5= 1111100
I know it has something to do with the way Matlab codes floting point numbers. Errors caused by quantification
Daniel Shub
Daniel Shub el 2 de Nov. de 2012
The point is that MATLAB cannot represent any of these numbers exactly. Therefore the number of decimal places is poorly defined.

Iniciar sesión para comentar.

Más respuestas (1)

Chris Taylor
Chris Taylor el 26 de Jul. de 2023
a = 11.111;
b = numdecpoints(a);
function f = numdecpoints(x)
i = -1;
X = 0;
while X ~= x
i = i + 1;
X = round(x, i);
end
f = i;
end
This seems to work, making use of MATLAB's round function. Not sure if it is the most efficient but seems to work for me. Simply compare the output of your original number and the number rounded to i decimal places. When the values match, i is the number of demical places in the orginal number.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by