代码改变世界

Java格式化输出

2011-02-24 13:29  RayLee  阅读(390)  评论(0编辑  收藏  举报

程序中常常遇见:控制数据格式化输出。而控制选项繁多,有时会忘记。该文做一个小结,作为以后参考引用。

整型数据(short, int等)

%d    A regular base-10 integer, such as 987

%o    A base-8 octal integer, such as 1733

%x    A base-16 lowercase hexadecimal integer, such as 3db

%X    A base-16 uppercase hexademical integer, such as 3DB

浮点型数据(float, double)

%f    A regular base-10 decimal number, such as 3.141593

%e    A decimal number in scientific notation with a lowercase e, such as 3.141593e+00

%E    A decimal number in scientific notation with an uppercase E, such as 3.141593E+00

%g    A decimal number formatted in either regular or scientific notation, depending on its size and precision, with a lowercase e if scientific notation is used

%G    A decimal number formatted in either regular or scientific notation, depending on its size and precision, with an uppercase E if scientific notation is used

%a    A lowercase hexadecimal floating-point number, such as 0x1.921fb54442d18p1

%A    An uppercase hexadecimal floating-point number, such as 0x1.921FB5442D18P1

对于浮点型数据,有时还需要控制输出的宽度,精度或者其它。这时需要用到格式修饰符(Format Modifiers)。格式修饰符遵照一定的模式:

%[argument_index$][flags][width][.precision]conversion

argument_index:    The number of the argument with which to replace this tag

flags:    Indicators of various formatting options

width:    The minimum number of characters with which to format the replacement value

precision:    The number of characters after the decimal point; alternatively, the maximum number of characters in the formatted string

Flag Signifies Applies to
- Left-justify All
# Alternate form General, integer, floating
+ Include a sign even if positive (Normally, only negative numbers have signs) Integer, floating point
space Add a leading space to positive numbers (This is where the sign would be and helps line up positive and negative numbers) Integer, floating point
0 Pad with zeros instead of spaces Integer, floating point
, Use the locale-specific grouping separator instead of a period Integer, floating point
# Use instead of a minus sign to indicate negative numbers Integer, floating point

尽管选项繁多,使用最多的还是控制输出的宽度和精度。

Example 1: 控制宽度和精度

System.out.printf(“%5.3f”, Math.PI),控制输出宽度为5,精度为3,结果为

“ 3.142”(输出的最前面有一个空格)

Example 2: 使用argument_index

System.out.printf(“%s and %s”, “You”, “Me”)输出”You and Me”

System.out.printf(“%2$s and %2$s”, “You”, “Me”)输出”Me and Me”