how can i compute the length of an integer?
显示 更早的评论
if i have
int = 12345;
length_int = 5;
???
采纳的回答
更多回答(2 个)
Sean de Wolski
2013-1-4
编辑:Sean de Wolski
2013-1-4
Edit
nnz(num2str(int) - '-')
4 个评论
Why this cast to an double array? Shouldn't
numel(num2str(int))
be enough?
Sean de Wolski
2013-1-4
Friedrich, neither work actually, consider -12345.
Friedrich
2013-1-4
Good point Sean. But then
numel(num2str(abs(int)))
should do ;)
Sean de Wolski
2013-1-4
arghh, you win!
Davide Ferraro
2013-1-4
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 个评论
why, it works:
>> int = 12345678901234567890123
numel(num2str(int))
int =
1.2346e+22
ans =
23
类别
在 帮助中心 和 File Exchange 中查找有关 Numeric Types 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!