Formateo con printf () en Java

1. Introducción

En este tutorial, demostraremos diferentes ejemplos de formateo con el método printf () .

El método es parte de la clase java.io.PrintStream y proporciona un formato de cadena similar a la función printf () en C.

2. Sintaxis

Podemos usar uno de los siguientes métodos PrintStream para formatear la salida:

System.out.printf(format, arguments); System.out.printf(locale, format, arguments);

Especificamos las reglas de formato usando el parámetro de formato . Las reglas comienzan con el carácter '%' .

Veamos un ejemplo rápido antes de profundizar en los detalles de las diversas reglas de formato:

System.out.printf("Hello %s!%n", "World");

Esto produce la siguiente salida:

Hello World!

Como se muestra arriba, la cadena de formato contiene texto sin formato y dos reglas de formato. La primera regla se utiliza para formatear el argumento de cadena. La segunda regla agrega un carácter de nueva línea al final de la cadena.

2.1. Reglas de formato

Echemos un vistazo a la cadena de formato más de cerca. Consiste en literales y especificadores de formato. Los especificadores de formato incluyen marcas, ancho, precisión y caracteres de conversión en la siguiente secuencia:

%[flags][width][.precision]conversion-character

Los especificadores entre paréntesis son opcionales.

Internamente, printf () usa la clase java.util.Formatter para analizar la cadena de formato y generar la salida. Se pueden encontrar opciones de cadena de formato adicionales en Formatter Javadoc.

2.2. Caracteres de conversión

El carácter de conversión es obligatorio y determina cómo se formatea el argumento . Los caracteres de conversión solo son válidos para ciertos tipos de datos. Algunos comunes son:

  • s - formatea cadenas
  • d - formatea enteros decimales
  • f - formatea los números de punto flotante
  • t - formatea los valores de fecha / hora

Exploraremos estos y algunos otros más adelante en el artículo.

2.3. Modificadores opcionales

Las [banderas] definen formas estándar de modificar la salida y son las más comunes para formatear números enteros y de coma flotante.

El [ancho] especifica el ancho del campo para generar el argumento. Representa el número mínimo de caracteres escritos en la salida.

[.Precision] especifica el número de dígitos de precisión cuando se generan valores de coma flotante. Además, podemos usarlo para definir la longitud de una subcadena para extraer de una Cadena .

3. Separador de líneas

Para dividir la cadena en líneas separadas, tenemos un especificador % n :

System.out.printf("baeldung%nline%nterminator");

El fragmento de código anterior producirá el siguiente resultado:

baeldung line terminator

El separador % n printf () insertará automáticamente el separador de línea nativo del sistema host .

4. Formato booleano

Para formatear valores booleanos, usamos el formato % b . Funciona de la siguiente manera: si el valor de entrada es verdadero , la salida es verdadera . De lo contrario, la salida es falsa .

Entonces, si lo hacemos:

System.out.printf("%b%n", null); System.out.printf("%B%n", false); System.out.printf("%B%n", 5.3); System.out.printf("%b%n", "random text");

Entonces veremos:

false FALSE TRUE true 

Observe que podemos usar % B para formatear en mayúsculas.

5. Formato de cadena

Para formatear una cadena simple, usaremos la combinación % s . Además, podemos poner la cadena en mayúsculas:

printf("'%s' %n", "baeldung"); printf("'%S' %n", "baeldung");

Y la salida es:

'baeldung' 'BAELDUNG'

Además, para especificar una longitud mínima, podemos especificar un ancho :

printf("'%15s' %n", "baeldung");

Lo que nos da:

' baeldung'

Si necesitamos justificar a la izquierda nuestra cadena, entonces podemos usar la bandera ' -' :

printf("'%-10s' %n", "baeldung");

Y la salida es:

'baeldung '

Even more, we can limit the number of characters in our output by specifying a precision:

System.out.printf("%2.2s", "Hi there!");

The first ‘x' number in %x.ys syntax is the padding. ‘y' is the number of chars.

For our example here, the output is Hi.

6. Char Formatting

The result of %c is a Unicode character:

System.out.printf("%c%n", 's'); System.out.printf("%C%n", 's');

The capital letter C will uppercase the result:

s S

But, if we give it an invalid argument, then Formatter will throw IllegalFormatConversionException.

7. Number Formatting

7.1. Integer Formatting

The printf() method accepts all the integers available in the language; byte, short, int, long and BigInteger if we use %d:

System.out.printf("simple integer: %d%n", 10000L);

With the help of the ‘d' character, we'll have:

simple integer: 10000

In case we need to format our number with the thousands separator, we can use the ‘,'flag. And we can also format our results for different locales:

System.out.printf(Locale.US, "%,d %n", 10000); System.out.printf(Locale.ITALY, "%,d %n", 10000);

As we see, the formatting in the US is different than in Italy:

10,000 10.000

7.2. Float and Double Formatting

To format a float number, we'll need the ‘f' format:

System.out.printf("%f%n", 5.1473);

Which will output:

5.147300

Of course, the first thing that comes to mind is to control the precision:

System.out.printf("'%5.2f'%n", 5.1473);

Here we define the width of our number as 5, and the length of the decimal part is 2:

' 5.15'

Here we have one space padding from the beginning of the number to support the predefined width.

To have our output in scientific notation, we just use the ‘e' conversion character:

System.out.printf("'%5.2e'%n", 5.1473);

And the result is the following:

'5.15e+00'

8. Date and Time Formatting

For date and time formatting, the conversion string is a sequence of two characters: the ‘t' or ‘T' character and the conversion suffix. Let's explore the most common time and date formatting suffix characters with the examples.

Definitely, for more advanced formatting we can use DateTimeFormatter which has been available since Java 8.

8.1. Time Formatting

First, let's see the list of some useful suffix characters for Time Formatting:

  • ‘H', ‘M', ‘S' – characters are responsible for extracting the hours, minutes and second from the input Date
  • ‘L', ‘N' – to represent the time in milliseconds and nanoseconds accordingly
  • ‘p' – adds am/pm formatting
  • ‘z' – prints out the timezone offset

Now, let's say we wanted to print out the time part of a Date:

Date date = new Date(); System.out.printf("%tT%n", date);

The code above along with ‘%tT' combination produces the following output:

13:51:15

In case we need more detailed formatting, we can call for different time segments:

System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);

Having used ‘H', ‘M', and ‘S' we get:

hours 13: minutes 51: seconds 15

Though, listing date multiple times is a pain. Alternatively, to get rid of multiple arguments, we can use the index reference of our input parameter which is 1$ in our case:

System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date);

Here we want as an output the current time, am/pm, time in milliseconds, nanoseconds and the timezone offset:

13:51:15 pm 061 061000000 +0400

8.2. Date Formatting

Like time formatting, we have special formatting characters for date formatting:

  • ‘A' – prints out the full day of the week
  • ‘d' – formats a two-digit day of the month
  • ‘B' – is for the full month name
  • ‘m' – formats a two-digit month
  • ‘Y' – outputs a year in four digits
  • ‘y' – outputs the last two digits of the year

So, if we wanted to show the day of the week, followed by the month:

System.out.printf("%1$tA, %1$tB %1$tY %n", date);

Then using ‘A', ‘B', and ‘Y', we'd get:

Thursday, November 2018

To have our results all in numeric format, we can replace the ‘A', ‘B', ‘Y ‘ letters with ‘d', ‘m', ‘y':

System.out.printf("%1$td.%1$tm.%1$ty %n", date);

Which will result in:

22.11.18

9. Summary

En este artículo, discutimos cómo usar el método PrintStream # printf para formatear la salida. Observamos los diferentes patrones de formato utilizados para controlar la salida de tipos de datos comunes.

Finalmente, como siempre, el código utilizado durante la discusión se puede encontrar en GitHub.