Asked by Zaza
on 4 Jan 2013

if i have

int = 12345;

length_int = 5;

???

Answer by Azzi Abdelmalek
on 4 Jan 2013

Edited by Azzi Abdelmalek
on 4 Jan 2013

Accepted Answer

int=-123456789

max(ceil(log10(abs(int))),1)

Sign in to comment.

Answer by Sean de Wolski
on 4 Jan 2013

Edited by Sean de Wolski
on 4 Jan 2013

Edit

nnz(num2str(int) - '-')

Sean de Wolski
on 4 Jan 2013

Friedrich, neither work actually, consider -12345.

Friedrich
on 4 Jan 2013

Good point Sean. But then

numel(num2str(abs(int)))

should do ;)

Sean de Wolski
on 4 Jan 2013

arghh, you win!

Sign in to comment.

Answer by Davide Ferraro
on 4 Jan 2013

Casting the variable into a string may be risky because you may get to "unexpected" cases such as:

int = 12345678901234567890123

numel(num2str(int))

ans =

12

You may consider a numeric approach using LOG10: floor(log10(int))+1 all numbers between 10 and 100 will have a LOG10 between 1 and 2 so you can use FLOOR to get the lower value (1 in this case) and then you need to add the value 1 cause you are trying to compute the number of digits and not the power of ten.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Jan (view profile)

Direct link to this comment:https://it.mathworks.com/matlabcentral/answers/57970-how-can-i-compute-the-length-of-an-integer#comment_120731

Sign in to comment.