Sample Java source code
package com.as400samplecode; public class AddLeadingZeros { public static void main(String[] args) { int myNumber = 654321; String stringNumber = String.format("%09d", myNumber); System.out.println("Number with leading zeros: " + stringNumber); } }
Program result
Number with leading zeros: 000654321Explanation
The format string can contain zero, one, or more format specifiers. The general form of a format specifier is:%[argument_index$][flags][width][.precision]conversion
where things in square brackets are optional, and conversion is a character indicating the conversion to be applied to the corresponding variable value. The only required characters in the format specifier is the percent sign % and the conversion character.
In the above example for converting a number to a string with leading zeros we used the following
- % sign
- flag "0" that make the result zero-padded
- width of 9
- "d" as the conversion
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.