日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java格式化输出

發布時間:2025/4/14 java 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java格式化输出 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

程序中常常遇見:控制數據格式化輸出。而控制選項繁多,有時會忘記。該文做一個小結,作為以后參考引用。

整型數據(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

FlagSignifiesApplies to
-Left-justifyAll
#Alternate formGeneral, integer, floating
+Include a sign even if positive (Normally, only negative numbers have signs)Integer, floating point
spaceAdd a leading space to positive numbers (This is where the sign would be and helps line up positive and negative numbers)Integer, floating point
0Pad with zeros instead of spacesInteger, floating point
,Use the locale-specific grouping separator instead of a periodInteger, floating point
#Use instead of a minus sign to indicate negative numbersInteger, 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”

轉載于:https://www.cnblogs.com/RayLee/archive/2011/02/24/1963687.html

總結

以上是生活随笔為你收集整理的Java格式化输出的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。