Java 输出格式化

10 Sept 2024 | 4 分钟阅读

有时我们希望程序的输出以指定的格式打印。在 C 编程语言中,这可以使用 printf() 函数实现。在本节中,我们将讨论不同的输出格式化。

让我们讨论如何在 Java 中格式化输出。

有两种方法可用于在 Java 中格式化输出:

  • 使用 printf() 方法
  • 使用 format() 方法

使用 System.out.printf() 方法格式化输出

此方法的实现非常简单,因为它与 C 编程中的 printf() 函数类似。

FormattedOutput1.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

输出

 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 :  $550,000.79 

Java 字符串格式说明符

在这里,我们提供一个 Java 字符串支持的格式说明符表。

格式说明符数据类型输出
%a浮点数(除 BigDecimal 外)返回浮点数的十六进制输出。
%b任何类型非 null 时为 "true",null 时为 "false"
%cCharacterUnicode 字符
%d整数(包括 byte、short、int、long、BigInteger)十进制整数
%e浮点数科学计数法表示的十进制数
%f浮点数十进制数
%g浮点数十进制数,根据精度和值可能采用科学计数法表示。
%h任何类型来自 hashCode() 方法的值的十六进制字符串。
%n特定于平台的换行符。
%o整数(包括 byte、short、int、long、BigInteger)八进制数
%s任何类型字符串值
%t日期/时间(包括 long、Calendar、Date 和 TemporalAccessor)%t 是日期/时间转换的前缀。之后需要更多的格式标志。请参阅下面的日期/时间转换。
%x整数(包括 byte、short、int、long、BigInteger)十六进制字符串。