I recently helped a colleague who had this simple requirement - to append zeros in front of a Number in a Java Method.
The purpose of the Method was to scan numbers between 1 and 999 and ensure that every number has three digits - the ones that have only two digits are appended by zeros.
The problem has multiple solutions & we were looking for the simplest possible solution. We tried a lot of solutions, starting with a simple for loop that counted the number of digits and appended zeros in front of it. We also looked at the Java API to see if a solution is already present.
However, we finalized two solutions that were very simple & elegant :-
Solution #1 ( JDK 1.5 onwards )
String.format("%03d", 1);
String.format("%03d", 10);
String.format("%03d", 100);
Solution #2 ( pre - JDK 1.5 )
NumberFormat objNumberFormat = new DecimalFormat("000");
objNumberFormat .format(Integer.parseInt( "1"));
objNumberFormat .format(Integer.parseInt( "10"));
objNumberFormat .format(Integer.parseInt( "100"));
We used Solution #2 to make the code reusable between JDK versions.
Monday, March 17, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment