Monday 27 May 2019

Java: Pad integer with zeros


Approach 1: Using String.format
String.format("%05d", yournumber);

App.java
package com.sample.app;

public class App {

 public static void main(String args[])  {
  int number1 = 1;
  int number2  = 12;
  int number3  = 123;
  int number4  = 1234;
  int number5  = 12345;
  
  String paddedData1 = String.format("%05d", number1);
  String paddedData2 = String.format("%05d", number2);
  String paddedData3 = String.format("%05d", number3);
  String paddedData4 = String.format("%05d", number4);
  String paddedData5 = String.format("%05d", number5);
  
  System.out.println("paddedData1 : " + paddedData1);
  System.out.println("paddedData2 : " + paddedData2);
  System.out.println("paddedData3 : " + paddedData3);
  System.out.println("paddedData4 : " + paddedData4);
  System.out.println("paddedData5 : " + paddedData5);

 }
}

Output
paddedData1 : 00001
paddedData2 : 00012
paddedData3 : 00123
paddedData4 : 01234
paddedData5 : 12345

Approach 2: Using DecimalFormat
DecimalFormat decimalFormat = new DecimalFormat("00000");
decimalFormat.format(1);
decimalFormat.format(12);


App.java
package com.sample.app;

import java.text.DecimalFormat;

public class App {

 public static void main(String args[])  {
  DecimalFormat decimalFormat = new DecimalFormat("00000");

  System.out.println("paddedData1 : " + decimalFormat.format(1));
  System.out.println("paddedData1 : " + decimalFormat.format(12));
  System.out.println("paddedData1 : " + decimalFormat.format(123));
  System.out.println("paddedData1 : " + decimalFormat.format(1234));
  System.out.println("paddedData1 : " + decimalFormat.format(12345));

 }
}


You may like

No comments:

Post a Comment