Skip to content

Instantly share code, notes, and snippets.

@jcchurch
Created August 24, 2016 02:16
Show Gist options
  • Save jcchurch/c7b6d3a2816f83e87b02b93bdbae0d86 to your computer and use it in GitHub Desktop.
Save jcchurch/c7b6d3a2816f83e87b02b93bdbae0d86 to your computer and use it in GitHub Desktop.
public class MyFormatter {
public static void main(String[] args) {
System.out.println(String.format("%s", "Hi Chris")); // "Hi Chris"
System.out.println(String.format("%d", 42)); // "42"
System.out.println(String.format("%f", Math.PI)); // "3.141593"
System.out.println();
System.out.println(String.format("%4d", 2)); // " 4"
System.out.println(String.format("%04d", 2)); // "0004"
System.out.println();
System.out.println(String.format("%.3f", Math.PI)); // "3.142"
System.out.println(String.format("%8.3f", Math.PI)); // " 3.142"
System.out.println(String.format("%08.3f", Math.PI)); // "0003.142"
System.out.println();
System.out.println(String.format("$%,.2f", 58000000.456)); // "$58,000,000.46"
System.out.println();
System.out.println(String.format("I am %d years old, I have $%,.2f in my wallet, and my name is %s.", 108, 58000000.456, "James"));
}
}
/*
This prints the following:
Hi Chris
42
3.141593
2
0002
3.142
3.142
0003.142
$58,000,000.46
I am 108 years old, I have $58,000,000.46 in my wallet, and my name is James.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment