how can i compute the length of an integer?

if i have
int = 12345;
length_int = 5;
???

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 1월 4일
편집: Azzi Abdelmalek 2013년 1월 4일

1 개 추천

int=-123456789
max(ceil(log10(abs(int))),1)

댓글 수: 1

this doesn't work for 10, 100, 1000...
for example max(ceil(log10(abs(10))),1) equals 1 but it should be 2
simple fix:
int = 10;
max(ceil(log10(abs(int)+1)),1)

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Sean de Wolski
Sean de Wolski 2013년 1월 4일
편집: Sean de Wolski 2013년 1월 4일

1 개 추천

Edit
nnz(num2str(int) - '-')

댓글 수: 4

Friedrich
Friedrich 2013년 1월 4일
편집: Friedrich 2013년 1월 4일
Why this cast to an double array? Shouldn't
numel(num2str(int))
be enough?
Friedrich, neither work actually, consider -12345.
Good point Sean. But then
numel(num2str(abs(int)))
should do ;)
arghh, you win!

댓글을 달려면 로그인하십시오.

Davide Ferraro
Davide Ferraro 2013년 1월 4일

0 개 추천

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.

댓글 수: 1

G A
G A 2013년 1월 4일
편집: G A 2013년 1월 4일
why, it works:
>> int = 12345678901234567890123
numel(num2str(int))
int =
1.2346e+22
ans =
23

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Numeric Types에 대해 자세히 알아보기

태그

질문:

2013년 1월 4일

댓글:

2020년 11월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by