logo

Форматування виводу Java

Іноді ми хочемо, щоб вихідні дані програми друкувались у заданому конкретному форматі. У мові програмування C це можливо за допомогою функції printf(). У цьому розділі ми обговоримо різне форматування виводу.

Давайте обговоримо, як ми можемо відформатувати вихідні дані в Java.

Є два методи, які можна використовувати для форматування виводу в Java:

np std
  • Використання методу printf().
  • Використання методу format().

Форматування виводу за допомогою методу System.out.printf().

Реалізація цього методу дуже проста, оскільки він схожий на функцію printf() у програмуванні на C.

FormattedOutput1.java

 public class FormattedOutput1 { public static void main( String args[ ] ) { // printing the string value on the console String str = ' JavaTpoint ' ; System.out.printf( ' 
 Printing the String value : %s 
 ', str ) ; // printing the integer value on the console int x = 512 ; System.out.printf( ' 
 Printing the integer value : x = %d 
 ', x ) ; // printing the decimal value on the console float f = 5.25412368f ; System.out.printf( ' 
 Printing the decimal value : %f 
 ', f ) ; // this formatting is used to specify the width un to which the digits can extend System.out.printf( ' 
 Formatting the output to specific width : n = %.4f 
 ', f ) ; // this formatting will print it up to 2 decimal places System.out.printf( ' 
 Formatted the output with precision : PI = %.2f 
 ', f ) ; // here number is formatted from right margin and occupies a width of 20 characters System.out.printf( ' 
 Formatted to right margin : n = %20.4f 
 ', f ) ; } } 

Вихід:

символ java до внутр
 Printing the String value : JavaTpoint Printing the integer value : x = 512 Printing the decimal value : 5.254124 Formatting the output to specific width : n = 5.2541 Formatted the output with precision : PI = 5.25 Formatted to right margin : n = 5.2541 

System.out.format() еквівалентний printf() і також може бути використаний.

Важливо зауважити, що System.out.print() і System.out.println() приймають один аргумент, але метод printf() може приймати кілька аргументів.

Форматування за допомогою класу DecimalFormat:

DecimalFormat використовується для форматування десяткових чисел.

FormattedOutput2.java

 import java.text.DecimalFormat ; // definition of the class public class FormattedOutput2 { public static void main( String args[ ] ) { double x = 123.4567 ; // printing the number System.out.printf( ' 
 The number is : %f 
 ', x ) ; // printing only the numeric part of the floating number DecimalFormat ft = new DecimalFormat( ' #### ' ) ; System.out.println( ' 
 Without fraction part the number is : ' + ft.format( x ) ) ; // printing the number only upto 2 decimal places ft = new DecimalFormat( ' #.## ' ) ; System.out.println( ' 
 Formatted number with the specified precision is = ' + ft.format( x ) ) ; // automatically appends zero to the rightmost part of decimal, instead of #, we use digit 0 ft = new DecimalFormat( ' #.000000 ' ) ; System.out.println( ' 
 Appending the zeroes to the right of the number = ' + ft.format( x ) ) ; // automatically appends zero to the leftmost of decimal number instead of #, we use digit 0 ft = new DecimalFormat( ' 00000.00 ' ) ; System.out.println( ' 
 Appending the zeroes to the left of the number = '+ ft.format( x ) ) ; // formatting money in dollars double income = 550000.789 ; ft = new DecimalFormat( ' $###,###.## ' ) ; System.out.println( ' 
 Your Formatted Income in Dollars : ' + ft.format( income ) ) ; } } 

Вихід:

 The number is : 123.456700 Without fraction part the number is : 123 Formatted number with the specified precision is = 123.46 Appending the zeroes to the right of the number = 123.456700 Appending the zeroes to the left of the number = 00123.46 Your Formatted Income in Dollars : 0,000.79 

Специфікатори формату рядка Java

Тут ми надаємо таблицю специфікаторів формату, які підтримуються Java String.

як вимкнути режим розробника на android
Специфікатор формату Тип даних Вихід
%a з плаваючою комою (крім BigDecima l) Повертає шістнадцяткове виведення числа з плаваючою комою.
%b Будь-який тип ' true ', якщо не null, ' false ', якщо null
%c характер символ Unicode
%d ціле число (включаючи байт, короткий, ціле, довгий, великий бінт) Десяткове ціле число
%Це є з плаваючою комою Десяткове число в науковій системі числення
%f з плаваючою комою Десяткове число
%g з плаваючою комою Десяткове число, можливо, у науковій нотації залежно від точності та значення.
%h будь-якого типу Шістнадцятковий рядок значення з методу hashCode().
%n жодного Спеціальний для платформи роздільник рядків.
%O ціле число (включаючи байт, короткий, ціле, довгий, великий бінт) Вісімкове число
%s будь-якого типу Рядкове значення
%t Дата/час (включаючи long, Calendar, Date і TemporalAccessor) %t є префіксом для перетворення дати/часу. Після цього потрібні додаткові позначки форматування. Дивіться перетворення дати/часу нижче.
%x ціле число (включаючи байт, короткий, ціле, довгий, великий бінт) Шістнадцятковий рядок.