Java格式化输出
程序中常常遇見:控制數(shù)據(jù)格式化輸出。而控制選項繁多,有時會忘記。該文做一個小結(jié),作為以后參考引用。
整型數(shù)據(jù)(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
浮點型數(shù)據(jù)(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
對于浮點型數(shù)據(jù),有時還需要控制輸出的寬度,精度或者其它。這時需要用到格式修飾符(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,結(jié)果為
“ 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”
轉(zhuǎn)載于:https://www.cnblogs.com/RayLee/archive/2011/02/24/1963687.html
總結(jié)
- 上一篇: ORA-07445 [kkoipt()+
- 下一篇: 算法导论第十二章:二叉查找树