Форматиране с printf () в Java

1. Въведение

В този урок ще демонстрират различни примери за форматиране с ФОРМАТ () метод .

Методът е част от класа java.io.PrintStream и осигурява форматиране на String, подобно на функцията printf () в C.

2. Синтаксис

Можем да използваме един от следните методи PrintStream за форматиране на изхода:

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

Ние определяме правилата за форматиране, като използваме параметъра format . Правилата започват с символа „%“ .

Нека разгледаме един бърз пример, преди да се впуснем в подробностите на различните правила за форматиране:

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

Това дава следния изход:

Hello World!

Както е показано по-горе, низът за форматиране съдържа обикновен текст и две правила за форматиране. Първото правило се използва за форматиране на аргумента на низа. Второто правило добавя символ на нов ред в края на низа.

2.1. Правила за форматиране

Нека да разгледаме по-отблизо форматиращия низ. Състои се от литерали и спецификатори на формат. Спецификаторите на формата включват знамена, ширина, точност и символи за преобразуване в следната последователност:

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

Спецификаторите в скобите не са задължителни.

Вътрешно printf () използва класа java.util.Formatter, за да анализира низа на формата и да генерира изхода. Допълнителни опции за форматиране на низове могат да бъдат намерени в Formatter Javadoc.

2.2. Преобразуващи символи

Символът за преобразуване е задължителен и определя начина на форматиране на аргумента . Символите за преобразуване са валидни само за определени типове данни. Някои често срещани са:

  • s - форматира низове
  • d - форматира десетични цели числа
  • f - форматира числата с плаваща запетая
  • t - форматира стойности за дата / час

Ще разгледаме тези и няколко други по-късно в статията.

2.3. Незадължителни модификатори

В [флагове] определят стандартните начини за промяна на изхода и са най-често за форматиране на числа и числа с плаваща запетая.

[Ширината] определя ширината на полето за извеждане на аргумента. Той представлява минималният брой символи, записани в изхода.

[.Precision] указва броя на цифрите с точност при извеждане на стойности с плаваща запетая. Освен това можем да го използваме, за да определим дължината на подниз, който да се извлече от низ .

3. Разделител на линии

За да разделим низа на отделни редове, имаме% n спецификатор :

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

Кодовият фрагмент по-горе ще даде следния изход:

baeldung line terminator

В % п сепаратор ФОРМАТ () автоматично ще вмъкне родния линия разделител на системата домакин .

4. Булево форматиране

За да форматираме булеви стойности, използваме формата % b . Работи по следния начин: Ако стойността на входа е вярна , изходът е истина . В противен случай изходът е невярен .

Така че, ако го направим:

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");

След това ще видим:

false FALSE TRUE true 

Забележете, че можем да използваме % B за форматиране на главни букви.

5. Форматиране на низове

За да форматираме обикновен низ, ще използваме комбинацията % s . Освен това можем да направим низа главни:

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

И изходът е:

'baeldung' 'BAELDUNG'

Също така, за да посочим минимална дължина, можем да посочим ширина :

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

Което ни дава:

' baeldung'

Ако трябва да подравним наляво нашия низ, тогава можем да използваме флага ' -' :

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

И изходът е:

'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

В тази статия обсъдихме как да използваме метода PrintStream # printf за форматиране на изхода. Разгледахме различните модели на формати, използвани за контрол на изхода за често срещани типове данни.

И накрая, както винаги, кодът, използван по време на дискусията, може да бъде намерен в GitHub.