Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.9k points)

Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)

static String intToString(int num, int digits) {

    StringBuffer s = new StringBuffer(digits);

    int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1; 

    for (int i = 0; i < zeroes; i++) {

        s.append(0);

    }

    return s.append(num).toString();

}

1 Answer

0 votes
by (46k points)

You can try String.format method:

In your situation it will be:

String formatted = String.format("%03d", num);

  • 0 - to pad with zeros

  • 3 - to set the width to 3

Check out this Java Doc for more info.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 14, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...