

The number itself has been rounded to 2 decimal places (with trailing zeros as needed) and is displayed with a comma separator (as needed). Note that each output String is 12 characters wide, with leading spaces inserted so that the number is right-justified within this width. This method is locale dependent as specified on the Locale argument. This method returns a String representation of the result of the object args based on the format specified on the method arguments.
#Java string format how to
The following code demonstrates the result, using an array of doubles as test data.ĭouble testData = This java tutorial shows how to use the format () method of String class of java.lang package. This class provides support for layout justification and alignment, common formats for numeric, string. This gives us a format string of "%,12.2f". An interpreter for printf-style format strings. Twelve spaces should ensure ample room for illustration purposes, so inserting a width component of "12" gives us a format string of "%12.2f".įinally, we'll add a flag component to include a locale-specific grouping separator (e.g., a comma separating thousands). Every method which produces formatted output requires a format string and an argument list. To do this, we only need to specify a maximum width using the component, because the default is to right-justify within that width. We've already ensured that there are exactly two digits to the right of the decimal, so what we really want is to right-justify within a column. Now, we also want to align on the decimal. So inserting ".2" gives us a format string of "%.2f". (Note the decimal point that flags this as a precision indicator.) Basically, this inserts trailing zeros or rounds as needed. Now, let's customize using the optional components.įirst, we'll want each of these to show 2 digits to the right of the decimal, so we'll add the component. Therefore, our format string is at least "%f".

In this case, we're dealing with floating point numbers, so we probably want a conversion character of f. The bracketed components are all optional, so at a minimum we need the percent sign followed by the appropriate conversion character.

In general, a format string (the first argument to String.format) for numeric material has the syntax:
