how can i compute the length of an integer?
51 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Zaza
le 4 Jan 2013
Commenté : Christian Ziegler
le 14 Nov 2020
if i have
int = 12345;
length_int = 5;
???
Réponse acceptée
Azzi Abdelmalek
le 4 Jan 2013
Modifié(e) : Azzi Abdelmalek
le 4 Jan 2013
int=-123456789
max(ceil(log10(abs(int))),1)
1 commentaire
Christian Ziegler
le 14 Nov 2020
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)
Plus de réponses (2)
Sean de Wolski
le 4 Jan 2013
Modifié(e) : Sean de Wolski
le 4 Jan 2013
Edit
nnz(num2str(int) - '-')
4 commentaires
Friedrich
le 4 Jan 2013
Good point Sean. But then
numel(num2str(abs(int)))
should do ;)
Davide Ferraro
le 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.
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!