Java add together leading zeros to a publish too convert to String

Sometimes during dealing alongside legacy systems nosotros take away to croak numeric values inwards fixed length alongside leading zeros. Now inwards Java nosotros simply convey an integer value. So how create nosotros convert an integer inwards Java to a string value alongside fixed length of ix alongside leading zeros. Here is a sample computer program that uses the String.format() method to add together leading zeros to a number.

Sample Java root code

package com.as400samplecode;  world shape AddLeadingZeros {      world static void main(String[] args) {          int myNumber = 654321;         String stringNumber = String.format("%09d", myNumber);         System.out.println("Number alongside leading zeros: " + stringNumber);             }  } 

Program result

Number alongside leading zeros: 000654321


The format string tin incorporate zero, one, or to a greater extent than format specifiers. The full general shape of a format specifier is:


where things inwards foursquare brackets are optional, together with conversion is a grapheme indicating the conversion to endure applied to the corresponding variable value. The solely required characters inwards the format specifier is the share sign % together with the conversion character.

In the higher upwards event for converting a release to a string alongside leading zeros nosotros used the following

  • % sign
  • flag “0” that brand the upshot zero-padded
  • width of 9
  • “d” every bit the conversion