Tuesday, October 16, 2012

Using String.format with Dates, Decimals and other cool things

Formatting Strings can become pretty cumbersome when you need to create a formatter object to handle a variety of different classes. Java does provide a pretty simple way to format many data types with the String.format method, but it can be hard to remember all the ways it can be used. Here are some examples to act as a reminder.


For more date/time formatting see here

Decimals and Money

Gotcha: If you are specifying each argument by it's index (%1, %2, etc) you need to add the '$' before any formatting, i.e. %2$.2f

Special Flags and New Line

You can also use special flags such as negative numbers in parans, zero-padding, and comma grouping
These examples cover the most common use cases of String formatting, but for more information you can check out the javadocs

No comments:

Post a Comment