Display numbers with leading zeros (0) in Java?

Possible duplicate:
Add number of zeros to number in Java?

Let's say I need to add two integers: 0001 and others 0002. If I add it in java then I get 3, but I would like 0003. Should I make a loop to display zeros or is it easier.

+3


source to share


3 answers


Do not confuse numbers with string representations of numbers. Your question revolves around the latter - how to represent a number as a string with leading zeros, and there are several possible solutions, including using a DecimalFormat object or String.format (...).

i.e.,



  int myInt = 5;
  String myStringRepOfInt = String.format("%05d", myInt);
  System.out.println("Using String.format: " + myStringRepOfInt);

  DecimalFormat decimalFormat = new DecimalFormat("00000");
  System.out.println("Using DecimalFormat: " + decimalFormat.format(myInt));

      

+14


source


you can add a left pane with zeros after you get the result.

String.format("%05d", result);

      



for zero padding with length = 5.

EDIT : I deleted the previous EDIT, it was completely wrong: @

+8


source


It will help you

String.format ( http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax )

In your case it would be: String.format ("% 03d", num) - 0 - to fill with zeros, 3 - to set the width to 3

0


source







All Articles