logo

Formatação de saída Java

Às vezes queremos que a saída de um programa seja impressa em um determinado formato específico. Na linguagem de programação C isso é possível usando a função printf(). Nesta seção, discutiremos as diferentes formatações de saída.

Vamos discutir como podemos formatar a saída em Java.

Existem dois métodos que podem ser usados ​​para formatar a saída em Java:

classificação por bolha em java
  • Usando o método printf()
  • Usando o método format()

Formatando a saída usando o método System.out.printf()

A implementação deste método é muito fácil, pois é semelhante à função printf() na programação C.

FormatadoOutput1.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 ) ; } } 

Saída:

 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( ) é equivalente a printf( ) e também pode ser usado.

Um ponto importante a ser observado é que System.out.print( ) e System.out.println( ) aceitam um único argumento, mas o método printf() pode aceitar vários argumentos.

aula de matemática java

Formatando usando a classe DecimalFormat:

DecimalFormat é usado para formatar números decimais.

FormatadoOutput2.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 ) ) ; } } 

Saída:

 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 

Especificadores de formato de string Java

Aqui, fornecemos uma tabela de especificadores de formato suportados pela Java String.

forma completa de i d e
Especificador de formato Tipo de dados Saída
%a ponto flutuante (exceto BigDecima l) Retorna a saída hexadecimal do número de ponto flutuante.
%b Qualquer tipo 'true' se não for nulo, 'false' se for nulo
%c Personagem Caractere Unicode
%d inteiro (incl. byte, curto, int, longo, bigint) Número inteiro decimal
%e ponto flutuante Número decimal em notação científica
%f ponto flutuante Número decimal
%g ponto flutuante Número decimal, possivelmente em notação científica dependendo da precisão e do valor.
%h qualquer tipo String hexadecimal de valor do método hashCode().
%n Nenhum Separador de linhas específico da plataforma.
%o inteiro (incl. byte, curto, int, longo, bigint) Número octal
%s qualquer tipo Valor da sequência
%t Data/Hora (incl. longo, Calendário, Data e TemporalAccessor) %t é o prefixo para conversões de data/hora. Mais sinalizadores de formatação serão necessários depois disso. Veja conversão de data/hora abaixo.
%x inteiro (incl. byte, curto, int, longo, bigint) Corda hexadecimal.