Java add leading zeros to a number
When areaCode is 0, you forget to call format
! Other than that, it looks fine. The leading "#" are not necessary, but won't cause any problems for valid inputs.
I just tried it out real quick to check and it worked fine for me.
public static String formatTest(int areaCode, int exchangeCode, int number) {
DecimalFormat nf3 = new DecimalFormat("#000");
DecimalFormat nf4 = new DecimalFormat("#0000");
if( areaCode != 0)
return nf3.format(areaCode) + "-" + nf3.format(exchangeCode) + "-" + nf4.format(number);
else
return nf3.format(exchangeCode) + "-" + nf4.format(number);
}
public static void main(String[] args) {
System.out.println(formatTest(12, 90, 8));
System.out.println(formatTest(1, 953, 1932));
}
Output:
012-090-0008
001-953-1932
There's an arguably more elegant solution:
String.format("%03d-%03d-%04d", areaCode, exchangeCode, number)