3

Possible Duplicate:
Add leading zeroes to number in Java?

Say that I have to add two integers one being 0001 and the other 0002. If I add it in java then I get 3 however I would like 0003. Would I have to make a loop to map out the zeros or is there an easier way.

Community
  • 1
  • 1
Tom
  • 515
  • 3
  • 7
  • 21
  • How do you add the integers `0001` and `0002`? – Gabe Apr 01 '12 at 04:11
  • Yep, what Hovercraft says -- you have two integers 1 and 2. The fact that they may be represented as 0001 and 0002 in some contexts has nothing to do with their actual values. – Hot Licks Apr 01 '12 at 04:13
  • 3
    Be careful! `0001` and `0002` are interpreted in Java as octal numbers since it starts with `0`, so `010` is actually `8` not `10`. – Eng.Fouad Apr 01 '12 at 04:14

3 Answers3

14

Don't confuse numbers with String representation 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));
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
8

you can add a left pad with zeros after having the result.

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

for zero-padding with length=5.

EDIT: i to removed the previous EDIT, it was totally wrong :@

imanis_tn
  • 1,150
  • 1
  • 12
  • 33
  • Your edit is completely wrong, and in fact your code in your original answer solves the problem that your edit messes up. Please run a small program to show to yourself that this is so. Sorry, but I must give you a -1 vote until you fix this error. – Hovercraft Full Of Eels Apr 01 '12 at 05:56
0

This will help you

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

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

Yogesh Prajapati
  • 4,770
  • 2
  • 36
  • 77