Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add leading zeroes to number in Java? [duplicate]

Tags:

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(); } 
like image 538
Nate Parsons Avatar asked Nov 09 '08 07:11

Nate Parsons


People also ask

How do you add a leading zero to a double in Java?

Yes, include the + character, e.g. String. format("%+014.2f", -2.34); .

How do you keep leading zeros in Java?

To display numbers with leading zeros in Java, useDecimalFormat("000000000000").

How can I pad a value with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.


2 Answers

String.format (https://docs.oracle.com/javase/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
like image 178
begray Avatar answered Oct 28 '22 05:10

begray


Since Java 1.5 you can use the String.format method. For example, to do the same thing as your example:

String format = String.format("%0%d", digits); String result = String.format(format, num); return result; 

In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:

%% --> % 0  --> 0 %d --> <value of digits> d  --> d 

So if digits is equal to 5, the format string becomes %05d which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format for more information on the conversion specifiers.

like image 37
Jason Coco Avatar answered Oct 28 '22 04:10

Jason Coco