Is there any single line of code that can be used to calculate the number of digits in a program? I mean to say, can be there a reference to a class (such as String.length for a String) which can be used to calculate the number of digits in a number?
Asked
Active
Viewed 595 times
-2
-
cast int to string and use this methog – Kick Mar 03 '14 at 17:10
-
Do you have the value as a number (int, long, double, char) or as a String? – Sotirios Delimanolis Mar 03 '14 at 17:10
-
http://stackoverflow.com/questions/1306727/way-to-get-number-of-digits-in-an-int – assylias Mar 03 '14 at 17:11
-
4Which type of number - there any many: integer, float, short, double, decimal... – Rich O'Kelly Mar 03 '14 at 17:11
-
no need for valueOf() despite most of the answers, ("" + number) is a string. – La-comadreja Mar 03 '14 at 17:13
-
I need to calculate the length of an Integer Number. – Niluu Mar 03 '14 at 17:13
-
Or is there any line of code to parse an Integer into a String? – Niluu Mar 03 '14 at 17:14
-
concatenate the integer to the end of an empty string: ("" + number) – La-comadreja Mar 03 '14 at 17:15
-
Just one last Question, is there a Syntax like (Integer. ...) – Niluu Mar 03 '14 at 17:17
-
This question was closed for the wrong reason: it's clear what this question is asking, and it's actually a duplicate of http://stackoverflow.com/questions/1306727/way-to-get-number-of-digits-in-an-int. – Anderson Green Mar 03 '14 at 17:26
7 Answers
6
If you want to avoid converting to a String
(and convert to a double
and back to an int
instead):
digits = int(Math.log10(a)) + 1;
If you also need to handle negative numbers:
digits = int(Math.log10(Math.abs(a))) + 1;
// uncomment the following line to count the negative sign as a digit
// if (a < 0) { digits += 1; }

Brigham
- 14,395
- 3
- 38
- 48
-
+1, as the log approach is about 20 times faster than the string conversion one. – Danstahr Mar 03 '14 at 17:19
-
1
1
Use
Math.floor(Math.log10(num)) + 1
for integers. Use
String.valueOf(num).length()
for anything else

PlasmaPower
- 1,864
- 15
- 18
0
int a = 125846;
System.out.println("Length is "+String.valueOf(a).length());
Output:
Length is 6

Uyghur Lives Matter
- 18,820
- 42
- 108
- 144

Kick
- 4,823
- 3
- 22
- 29
0
int bubba = 56733;
System.out.println(String.valueOf(bubba).length());
Output: 5

Solace
- 2,161
- 1
- 16
- 33
0
Integer.toString(19991).length();

Graham Griffiths
- 2,196
- 1
- 12
- 15
-
-
The method is called `toString()`. Remember that Java convention is that method starts with lowercase, classes with uppercase. – Christian Tapia Mar 03 '14 at 17:23
-