Wednesday, 18 October 2017

Add leading zeroes to number in Java?





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();
}


Answer




String.format ( href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax"
rel="noreferrer">http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax)




In
your case it will be:



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



  • 0
    - to pad with zeros

  • 3 - to set width to
    3


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...