Skip to content

Instantly share code, notes, and snippets.

@huljas
Created August 3, 2011 13:24
Show Gist options
  • Save huljas/1122618 to your computer and use it in GitHub Desktop.
Save huljas/1122618 to your computer and use it in GitHub Desktop.
Most common formats for String.format(..)
import org.junit.Test;
import java.util.Date;
import static org.junit.Assert.assertEquals;
public class StringFormatTest {
@Test public void basicInteger() {
assertEquals("123456", String.format("%d", 123456));
}
@Test public void leftPaddingIntegerWithZeroes() {
assertEquals("007", String.format("%03d", 7));
}
@Test public void integerWithLeadingSpace() {
assertEquals(" 11", String.format("% 4d", 11));
}
@Test public void floatWithTwoDecimals() {
assertEquals("1123.35", String.format("%.2f", 1123.345566));
}
@Test public void time() {
assertEquals("09:26:42", String.format("%tT", 1312180002230L));
}
@Test public void date() {
assertEquals("2011-08-01", String.format("%tF", new Date(1312180002230L)));
}
@Test public void dateAndTime() {
assertEquals("09:26:42.231 2011.08.01", String.format("%1$tH:%1$tM:%1$tS.%1$tL %1$tY.%1$tm.%1$td", 1312180002231L));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment