Left pad zeros and save the result as Integer in java.

141 views Asked by At

Here is my code

Integer.pasrseInt(new DecimalFormat(0000).format(230));

This returns a String but I want to save it as an Integer.

Thanks in advance.

2

There are 2 answers

0
Keerthivasan On

The best way it that you can prepend 0s if the characters are less than 4. Integers cannot have 0 in front. AFAIK, only String objects can be created by prepending 0s to integers. Note, when you convert the String back to Integer, the prepended zeros will be removed.

0
Averroes On

Maybe it's an overkill but maybe this give you an idea of why you cannot directly do what you asked:

public class MyInteger {

private Integer value;

public MyInteger(Integer value){
  this.value = value;
}

public String showWithPad(){
  return DecimalFormat(0000).format(value);
}

}

Then you do

MyInteger myInteger = new MyInteger(230);
System.out.println(myInteger.showWithPad());

And this prints

0230

As it was stated you cannot pad an Integer but its representation (eg the way you show it). Then you have to store the number as is (an Integer) and add the padding zeros when you want to represent it this way.