Find the number of decimal digits of a variable in MATLAB

Given the variable x = 12.3442

I want to know the number of decimal digits of a variable. In this case, the result will be 4. How can I do this without trial and error?

+6
source share
5 answers

Here is a compact way:

y = x.*10.^(1:20) find(y==round(y),1) 

Assumes x is your number and 20 is the maximum number of decimal places.

+5
source

As mentioned in the comments, the β€œnumber of decimal digits” in most cases does not make sense, but I think this may be what you are looking for:

 >> num = 1.23400; >> temp = regexp(num2str(num),'\.','split') temp = '1' '234' >> length(temp{2}) ans = 3 
+3
source
 %If number is less than zero, we need to work with absolute value if(value < 0) num = abs(value); else num = value; end d = 0; % no of places after decimal initialised to 0. x = floor(num); diff = num - x; while(diff > 0) d = d + 1; num = num * 10; x = floor(num); diff = num - x; end %d is the required digits after decimal point 
0
source

For the number a , the assumption that it will have less than 28 decimal places is something compact and reliable:

 numDP = length(num2str(a, 28)) - strfind(num2str(a, 28),'.'); 

Converting to string makes good use of string comparison functions in Matlab, although it's a bit awkward.

0
source

It works under all conditions (if it is decimal):

 temp = strsplit(num2str(num),'.'); result = length(temp{2}); 
0
source

Source: https://habr.com/ru/post/944899/


All Articles