Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

Counting the number of digits

Asked by joseph Frank

joseph Frank (view profile)

on 3 Jul 2011
Accepted Answer by bym

bym (view profile)

Hi,

how can I compute the number of digits A=[12875] how can I get 5 as the number of digits in A?

0 Comments

joseph Frank

joseph Frank (view profile)

Tags

Products

No products are associated with this question.

5 Answers

Answer by bym

bym (view profile)

on 3 Jul 2011
Accepted answer

One way:

numel(num2str(A))

3 Comments

Paulo Silva

Paulo Silva (view profile)

on 3 Jul 2011

I made the stupid mistake of using -'0' when it wasn't needed so I'm voting on your answer and removing mine.

Oleg Komarov

Oleg Komarov (view profile)

on 3 Jul 2011

Fails with decimals. Ex: n = 99.3;

Walter Roberson

Walter Roberson (view profile)

on 15 Jul 2011

Fails with negative numbers too.

bym

bym (view profile)

Answer by Oleg Komarov

Oleg Komarov (view profile)

on 3 Jul 2011

To count integer part

ceil(log10(abs(A)))

Edit

floor(log10(abs(A)+1)) + 1

3 Comments

Walter Roberson

Walter Roberson (view profile)

on 15 Jul 2011

Fails on [-1,1] and all exact powers of 10.

Jan Simon

Jan Simon (view profile)

on 15 Jul 2011

ceil(log10(abs(A) + 1)) ?

Walter Roberson

Walter Roberson (view profile)

on 15 Jul 2011

Fails on 0, Jan.

Over integral values:

ceil(log10(max(1,abs(A)+1)))

Over real numbers,

ceil(log10(max(1,abs(A)*(1+eps))))

I think.

Oleg Komarov

Oleg Komarov (view profile)

Answer by Jaymin

Jaymin (view profile)

on 13 Dec 2012

Long, but it gets the job done.

numel(num2str(A))-numel(strfind(num2str(A),'-'))-numel(strfind(num2str(A),'.'))

0 Comments

Jaymin

Jaymin (view profile)

Answer by Stephanie

Stephanie (view profile)

on 26 May 2013
numel(num2str(fix(abs(A))))

0 Comments

Stephanie

Stephanie (view profile)

Answer by Turner

Turner (view profile)

on 16 Aug 2013
Edited by Turner

Turner (view profile)

on 19 Aug 2013

Will do the trick for all nonzero integers:

fix(abs(log10(abs(A))))+1

For a 10,000 iteration benchmark with some above answers:

Jaymin= 1.423717 seconds; Stephanie= 0.476135 seconds; Mine= 0.000878 seconds

If you don't expect 0s to appear, this is the fastest and most accurate method. Only works for decimals that satisfy -1<A<1.

0 Comments

Turner

Turner (view profile)

Contact us