Documentation

The Java™ Tutorials
Hide TOC
Formatting Numeric Print Output格式化数字打印输出
Trail: Learning the Java Language
Lesson: Numbers and Strings
Section: Numbers

Formatting Numeric Print Output格式化数字打印输出

Earlier you saw the use of the print and println methods for printing strings to standard output (System.out).早些时候,您看到了使用printprintln方法将字符串打印到标准输出(System.out)。Since all numbers can be converted to strings (as you will see later in this lesson), you can use these methods to print out an arbitrary mixture of strings and numbers.由于所有数字都可以转换为字符串(您将在本课后面看到),因此可以使用这些方法打印字符串和数字的任意组合。The Java programming language has other methods, however, that allow you to exercise much more control over your print output when numbers are included.但是,Java编程语言还有其他方法,允许您在包含数字时对打印输出进行更多的控制。

The printf and format Methodsprintfformat方法

The java.io package includes a PrintStream class that has two formatting methods that you can use to replace print and println.java.io包包括一个PrintStream类,该类有两种格式化方法,可用于替换printprintlnThese methods, format and printf, are equivalent to one another.formatprintf这两种方法彼此等效。The familiar System.out that you have been using happens to be a PrintStream object, so you can invoke PrintStream methods on System.out.您所使用的熟悉的System.out恰好是一个PrintStream对象,因此您可以在System.out上调用PrintStream方法。Thus, you can use format or printf anywhere in your code where you have previously been using print or println.因此,您可以在代码中以前使用过printprintln的任何地方使用formatprintfFor example,例如

System.out.format(.....);

The syntax for these two java.io.PrintStream methods is the same:这两个java.io.PrintStream方法的语法相同:

public PrintStream format(String format, Object... args)

where format is a string that specifies the formatting to be used and args is a list of the variables to be printed using that formatting.其中format是一个字符串,指定要使用的格式,args是要使用该格式打印的变量列表。A simple example would be一个简单的例子是

System.out.format("The value of " + "the float variable is " +
     "%f, while the value of the " + "integer variable is %d, " +
     "and the string is %s", floatVar, intVar, stringVar);

The first parameter, format, is a format string specifying how the objects in the second parameter, args, are to be formatted.第一个参数format是一个格式字符串,指定如何格式化第二个参数args中的对象。The format string contains plain text as well as format specifiers, which are special characters that format the arguments of Object... args.格式字符串包含纯文本和格式说明符,它们是格式化Object... args参数的特殊字符。(The notation Object... args is called varargs, which means that the number of arguments may vary.)(符号Object... args称为varargs,这意味着参数的数量可能会有所不同。)

Format specifiers begin with a percent sign (%) and end with a converter.格式说明符以百分号(%)开头,以转换器结尾。The converter is a character indicating the type of argument to be formatted.转换器是一个字符,指示要格式化的参数类型。In between the percent sign (%) and the converter you can have optional flags and specifiers.在百分号(%)和转换器之间,可以有可选的标志和说明符。There are many converters, flags, and specifiers, which are documented in java.util.Formatterjava.util.Formatter中记录了许多转换器、标志和说明符

Here is a basic example:以下是一个基本示例:

int i = 461012;
System.out.format("The value of i is: %d%n", i);

The %d specifies that the single variable is a decimal integer.%d指定单个变量为十进制整数。The %n is a platform-independent newline character.%n是独立于平台的换行符。The output is:输出为:

The value of i is: 461012

The printf and format methods are overloaded.printfformat方法重载。Each has a version with the following syntax:每个版本都有一个具有以下语法的版本:

public PrintStream format(Locale l, String format, Object... args)

To print numbers in the French system (where a comma is used in place of the decimal place in the English representation of floating point numbers), for example, you would use:例如,要在法语系统中打印数字(在英文浮点数表示法中,逗号用于替换小数点),您可以使用:

System.out.format(Locale.FRANCE,
    "The value of the float " + "variable is %f, while the " +
    "value of the integer variable " + "is %d, and the string is %s%n", 
    floatVar, intVar, stringVar);

An Example一个例子

The following table lists some of the converters and flags that are used in the sample program, TestFormat.java, that follows the table.下表列出了下表后面的示例程序TestFormat.java中使用的一些转换器和标志。

Converters and Flags Used in TestFormat.javaTestFormat.java中使用的转换器和标志
Converter转换器 Flag标志 Explanation解释
d   A decimal integer.十进制整数。
f   A float.浮点数。
n   A new line character appropriate to the platform running the application.适用于运行应用程序的平台的新行字符。You should always use %n, rather than \n.您应该始终使用%n,而不是\n
tB   A date & time conversion—locale-specific full name of month.日期和时间转换—特定于区域设置的月份全名。
td, te   A date & time conversion日期和时间转换2-digit day of month.2位数的月份日期。td has leading zeroes as needed, te does not.td根据需要有前导零,te没有。
ty, tY   A date & time conversion日期和时间转换ty = 2-digit year, tY = 4-digit year.ty=两位数年份,ty=四位数年份。
tl   A date & time conversion日期和时间转换hour in 12-hour clock.12小时钟中的一小时。
tM   A date & time conversion日期和时间转换minutes in 2 digits, with leading zeroes as necessary.分为两位数,必要时带前导零。
tp   A date & time conversion日期和时间转换locale-specific am/pm (lower case).特定于区域设置的am/pm(小写)。
tm   A date & time conversion日期和时间转换months in 2 digits, with leading zeroes as necessary.以2位数字表示的月份,必要时带前导零。
tD   A date & time conversion日期和时间转换date as %tm%td%ty%tm%td%ty形式的日期
  08 Eight characters in width, with leading zeroes as necessary.八个字符宽,必要时带前导零。
  + Includes sign, whether positive or negative.包括正负号。
  , Includes locale-specific grouping characters.包括特定于区域设置的分组字符。
  - Left-justified..左对齐……
  .3 Three places after decimal point.小数点后三位。
  10.3 Ten characters in width, right justified, with three places after decimal point.宽度为十个字符,右对齐,小数点后三位。

The following program shows some of the formatting that you can do with format.下面的程序显示了可以使用format进行的一些格式化。The output is shown within double quotes in the embedded comment:输出显示在嵌入注释的双引号内:

import java.util.Calendar;
import java.util.Locale;

public class TestFormat {
    
    public static void main(String[] args) {
      long n = 461012;
      System.out.format("%d%n", n);      //  -->  "461012"
      System.out.format("%08d%n", n);    //  -->  "00461012"
      System.out.format("%+8d%n", n);    //  -->  " +461012"
      System.out.format("%,8d%n", n);    // -->  " 461,012"
      System.out.format("%+,8d%n%n", n); //  -->  "+461,012"
      
      double pi = Math.PI;

      System.out.format("%f%n", pi);       // -->  "3.141593"
      System.out.format("%.3f%n", pi);     // -->  "3.142"
      System.out.format("%10.3f%n", pi);   // -->  "     3.142"
      System.out.format("%-10.3f%n", pi);  // -->  "3.142"
      System.out.format(Locale.FRANCE,
                        "%-10.4f%n%n", pi); // -->  "3,1416"

      Calendar c = Calendar.getInstance();
      System.out.format("%tB %te, %tY%n", c, c, c); // -->  "May 29, 2006"

      System.out.format("%tl:%tM %tp%n", c, c, c);  // -->  "2:34 am"

      System.out.format("%tD%n", c);    // -->  "05/29/06"
    }
}

Note:  The discussion in this section covers just the basics of the format and printf methods.本节中的讨论仅涵盖format方法和printf方法的基础知识。Further detail can be found in the Basic I/O section of the Essential trail, in the "Formatting" page.更多详细信息,请参阅Essential trail的基本I/O部分的“格式化”页面。
Using String.format to create strings is covered in Strings.字符串中介绍了使用String.format创建字符串。

The DecimalFormat ClassDecimalFormat

You can use the java.text.DecimalFormat class to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator.您可以使用java.text.DecimalFormat类来控制前导零和尾随零、前缀和后缀、分组(千)分隔符和十进制分隔符的显示。DecimalFormat offers a great deal of flexibility in the formatting of numbers, but it can make your code more complex.DecimalFormat在数字格式方面提供了很大的灵活性,但它会使代码更加复杂。

The example that follows creates a DecimalFormat object, myFormatter, by passing a pattern string to the DecimalFormat constructor.下面的示例通过将模式字符串传递给DecimalFormat构造函数来创建DecimalFormat对象myFormatterThe format() method, which DecimalFormat inherits from NumberFormat, is then invoked by myFormatterDecimalFormatNumberFormat继承的format()方法随后由myFormatter调用it accepts a double value as an argument and returns the formatted number in a string:它接受double值作为参数,并以字符串形式返回格式化的数字:

Here is a sample program that illustrates the use of DecimalFormat:下面是一个示例程序,演示了DecimalFormat的使用:

import java.text.*;

public class DecimalFormatDemo {

   static public void customFormat(String pattern, double value ) {
      DecimalFormat myFormatter = new DecimalFormat(pattern);
      String output = myFormatter.format(value);
      System.out.println(value + "  " + pattern + "  " + output);
   }

   static public void main(String[] args) {

      customFormat("
,
.
", 123456.789);
      customFormat("
.##", 123456.789);
      customFormat("000000.000", 123.78);
      customFormat("$
,
.
", 12345.67);  
   }
}

The output is:输出为:

123456.789  
,
.
  123,456.789
123456.789  
.##  123456.79
123.78  000000.000  000123.780
12345.67  $
,
.
  $12,345.67

The following table explains each line of output.下表解释了每行输出。

DecimalFormat.java Output输出
Value Pattern模式 Output输出 Explanation解释
123456.789 , . 123,456.789 The pound sign (#) denotes a digit, the comma is a placeholder for the grouping separator, and the period is a placeholder for the decimal separator.磅符号(#)表示数字,逗号是分组分隔符的占位符,句点是十进制分隔符的占位符。
123456.789 .## 123456.79 The value has three digits to the right of the decimal point, but the pattern has only two.value在小数点右侧有三位数字,但pattern只有两位。The format method handles this by rounding up.format方法通过向上取整来处理此问题。
123.78 000000.000 000123.780 The pattern specifies leading and trailing zeros, because the 0 character is used instead of the pound sign (#).pattern指定前导零和尾随零,因为使用0字符而不是磅符号(#)。
12345.67 $ , . $12,345.67 The first character in the pattern is the dollar sign ($).pattern中的第一个字符是美元符号($)。Note that it immediately precedes the leftmost digit in the formatted output.请注意,它紧跟在格式化output中最左边的数字之前。

Previous page: The Numbers Classes
Next page: Beyond Basic Arithmetic