1

I am creating a function that counts the number of digits in an integer. The answer keeps coming out as zero however. It's late and I am probably overlooking something very simple. Thanks.

function [ count ] = CountDigits( input )

s = int2str(input);      % convert the input to a string
count = 0;               % initialize count to zero
n = length(s);           % total length of s

    for k = 1 : 1 : n
        if s(1,k) >= '0' && s(1,k) <= '9'           % is digit
            count = count + 1;                      % add to count if digit
        end
    end
end
4

2 回答 2

4

I think you're overlooking something straightforward like

floor(log10(abs(your_integer_here))+1)
于 2013-11-07T08:46:42.183 回答
3

numel(num2str(abs(your_integer_here))) 成功了。

于 2013-11-07T09:19:50.813 回答