Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the number of digits in an int

Tags:

How do I detect the length of an integer? In case I had le: int test(234567545);

How do I know how long the int is? Like telling me there is 9 numbers inside it???

*I have tried:**

char buffer_length[100];


    //  assign directly to a string.

    sprintf(buffer_length, "%d\n", 234567545);

    string sf = buffer_length;


    cout <<sf.length()-1 << endl;

But there must be a simpler way of doing it or more clean...

like image 419
user1417815 Avatar asked Jun 22 '12 07:06

user1417815


People also ask

How do you extract the number of digits in a number?

Extracting digits of a number is very simple. When you divide a number by 10, the remainder is the digit in the unit's place. You got your digit, now if you perform integer division on the number by 10, it will truncate the number by removing the digit you just extracted.

How do you count the number of digits in an integer in Python?

The len() function is a built-in function in Python used to calculate the number of characters inside a string variable. The len() function takes a string as an input parameter and returns the number of characters inside that string.

How many digits is an int Java?

int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1.


1 Answers

How about division:

int length = 1;
int x = 234567545;
while ( x /= 10 )
   length++;

or use the log10 method from <math.h>.

Note that log10 returns a double, so you'll have to adjust the result.

like image 93
Luchian Grigore Avatar answered Oct 08 '22 08:10

Luchian Grigore