-1

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
  • 11
  • 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,045
  • 3
  • 36
  • 47
1
int len = ("" + number).length();
La-comadreja
  • 5,447
  • 9
  • 34
  • 61
1

Use

Math.floor(Math.log10(num)) + 1

for integers. Use

String.valueOf(num).length()

for anything else

PlasmaPower
  • 1,826
  • 13
  • 17
0
int a = 125846;
System.out.println("Length is "+String.valueOf(a).length());

Output:

Length is 6
Uyghur Lives Matter
  • 17,261
  • 40
  • 105
  • 135
Kick
  • 4,742
  • 2
  • 20
  • 25
0
int bubba = 56733;
System.out.println(String.valueOf(bubba).length());

Output: 5

Solace
  • 2,151
  • 1
  • 14
  • 32
0

You could always do something like String.valueOf(

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