0 votes
1 view
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 (46.1k 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)
0 votes
1 answer
asked Aug 16, 2019 in Java by Shubham (3.9k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...