Wednesday, July 12, 2006

Zero-left-padding with java.text.ChoiceFormat

Sheesh.

After a cursory search, I couldn't find any examples of how to format new Integer(7) as "007" in Java. So I snooped around the java.text package JavaDocs and got this test to pass:

-snip-
import java.text.ChoiceFormat;

import junit.framework.TestCase;

public class RemoteAddressToInetAddressUnit extends TestCase
{
public void testDotNotationStringToBigNumberThingy()
{
ChoiceFormat formatter = new ChoiceFormat("0#00|9<0|99<");

String[] splitAddress = "127.0.0.1".split("\\.");

StringBuilder sb = new StringBuilder("");

for (int i = 0; i < splitAddress.length; i++)
{
sb.append(formatter.format(Integer.parseInt(splitAddress[i])));
sb.append(splitAddress[i]);
}

assertEquals("127000000001", sb.toString());
}
}
-snip-

It seems like there should be an easier way to do this, and I'm sure there is. But there it is.

Grrr.

0 Comments:

Post a Comment

<< Home