dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Counting Digits in a Given Number

Learn how to use a combination of methods in Math package to count digits.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


A typical mechanism of converting to a string, traversing and counting has a lot of processing to complete.

Instead, the code below shows a combination of methods in Math package to help us achieve the same.

*/

public class DigitCount
{
   public static void main(String args[])
   {
      DigitCount digitCount = new DigitCount();
      digitCount.proceed();
   }
   
   private void proceed()
   {
      int aNumber = 56554;
      System.out.println("Digit count in " + aNumber + ": " + Math.round(Math.floor(Math.log10(aNumber)) + 1));
   }
}

/*

Expected output:

[root@mypc]# java DigitCount
Digit count in 56554: 5

*/ 

 

Visit the DevX Tip Bank

 





   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Thanks for your registration, follow us on our social networks to keep up-to-date