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

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

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2012-11-2
编辑:Azzi Abdelmalek 2012-11-2
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 个评论
Azzi Abdelmalek
Azzi Abdelmalek 2012-11-2
编辑:Azzi Abdelmalek 2012-11-2
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 2012-11-2
The point is that MATLAB cannot represent any of these numbers exactly. Therefore the number of decimal places is poorly defined.

请先登录,再进行评论。

更多回答(1 个)

Chris Taylor
Chris Taylor 2023-7-26
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.

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by