-2

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?

Niluu
  • 9
  • 2

7 Answers7

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
int len = ("" + number).length();
La-comadreja
  • 5,627
  • 11
  • 36
  • 64
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

You could always do something like String.valueOf(

0
Integer.toString(19991).length();
Graham Griffiths
  • 2,196
  • 1
  • 12
  • 15