2 Replies - 1735 Views - Last Post: 28 May 2011 - 02:31 PM Rate Topic: -----

#1 anonymous26   User is offline

  • D.I.C Lover

Reputation: 2
  • View blog
  • Posts: 3,638
  • Joined: 26-November 10

How many digits in a number?

Posted 28 May 2011 - 05:12 AM

Description: This was built using gcc (-lm linker option). Set 'myNumber' to any value in the range representable by a signed long for your setup.This code gives you the number of digits in an signed long. It completely eliminates the requirement to use loops to successively divide and mod by ten which is often an unreliable method.
#include <stdio.h>
#include <math.h>

int main()
{
    long myNumber = 145634521;    // Set to any number that can be represented by signed long.

    if(myNumber < 0)
        myNumber = abs(myNumber);

    long numDigits = myNumber > 0 ? log10(myNumber) + 1 : 1;

    printf("Number of digits is %ldn", numDigits);

    return 0;
}


Is This A Good Question/Topic? 0
  • +

Replies To: How many digits in a number?

#2 ishkabible   User is offline

  • spelling expret
  • member icon





Reputation: 1747
  • View blog
  • Posts: 5,898
  • Joined: 03-August 09

Re: How many digits in a number?

Posted 28 May 2011 - 02:26 PM

glad to see you got this snippet up ;)
Was This Post Helpful? 0
  • +
  • -

#3 anonymous26   User is offline

  • D.I.C Lover

Reputation: 2
  • View blog
  • Posts: 3,638
  • Joined: 26-November 10

Re: How many digits in a number?

Posted 28 May 2011 - 02:31 PM

Thanks! Notice that it now uses longs and handles negative numbers too? :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1