Search code examples
countnumberscountingdigits

Easiest way to count digits in number


Recently, while doing a printer layout programmatically in Java, I stumbled across the problem of aligning certain numbers and to have them right-aligned I needed to have a count of the amount of digits in each number. What would be the easiest way to do this?


Solution

  • While I was breaking my head over an algorithm on how to do this the simplest, a friend of mine pointed out a very simple solution: simply put the number in a string and count its length ;-). No need to make things hard on yourself with mathematical formulas! In Java for example:

    String number_s = ""+number;
    int digits = number_s.length();
    

    This can be applied to decimal numbers aswell, after splitting the string on the separating delimiter (usually . or ,).

    Hope I can save at least someone some time with this.