本文列舉了幾個(gè)方法:
1. 使用java.math.BigDecimal
2. 使用java.text.DecimalFormat
3. 使用java.text.NumberFormat
4. 使用java.util.Formatter
5. 使用String.format
文章末尾給大家分享了更多的拓展知識(shí),另外可以自己實(shí)現(xiàn)或者借用封裝好的類庫(kù)來實(shí)現(xiàn),在這篇文章中就不一一列舉了。 下面來看看詳細(xì)的介紹。
一、使用BigDecimal,保留小數(shù)點(diǎn)后兩位
1
2
3
4
5
6
|
public static String format1( double value) { BigDecimal bd = new BigDecimal(value); bd = bd.setScale( 2 , RoundingMode.HALF_UP); return bd.toString(); } |
二、使用DecimalFormat,保留小數(shù)點(diǎn)后兩位
1
2
3
4
5
6
|
public static String format2( double value) { DecimalFormat df = new DecimalFormat( "0.00" ); df.setRoundingMode(RoundingMode.HALF_UP); return df.format(value); } |
三、使用NumberFormat,保留小數(shù)點(diǎn)后兩位
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public static String format3( double value) { NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits( 2 ); /* * setMinimumFractionDigits設(shè)置成2 * * 如果不這么做,那么當(dāng)value的值是100.00的時(shí)候返回100 * * 而不是100.00 */ nf.setMinimumFractionDigits(2); nf.setRoundingMode(RoundingMode.HALF_UP); /* * 如果想輸出的格式用逗號(hào)隔開,可以設(shè)置成true */ nf.setGroupingUsed( false ); return nf.format(value); } |
四、使用java.util.Formatter,保留小數(shù)點(diǎn)后兩位
1
2
3
4
5
6
|
public static String format4( double value) { /* * %.2f % 表示 小數(shù)點(diǎn)前任意位數(shù) 2 表示兩位小數(shù) 格式后的結(jié)果為 f 表示浮點(diǎn)型 */ return new Formatter().format( "%.2f" , value).toString(); } |
五、使用String.format來實(shí)現(xiàn)。
1
2
3
4
|
public static String format5( double value) { return String.format( "%.2f" , value).toString(); } |
擴(kuò)展知識(shí)
String.format
作為文本處理工具,為我們提供強(qiáng)大而豐富的字符串格式化功能。
對(duì)浮點(diǎn)數(shù)進(jìn)行格式化
占位符格式為: %[index$][標(biāo)識(shí)]*[最小寬度][.精度]轉(zhuǎn)換符
1
2
3
4
|
double num = 123.4567899 ; System.out.print(String.format( "%f %n" , num)); // 123.456790 System.out.print(String.format( "%a %n" , num)); // 0x1.edd3c0bb46929p6 System.out.print(String.format( "%g %n" , num)); // 123.457 |
可用標(biāo)識(shí):
-,在最小寬度內(nèi)左對(duì)齊,不可以與0標(biāo)識(shí)一起使用。
0,若內(nèi)容長(zhǎng)度不足最小寬度,則在左邊用0來填充。
#,對(duì)8進(jìn)制和16進(jìn)制,8進(jìn)制前添加一個(gè)0,16進(jìn)制前添加0x。
+,結(jié)果總包含一個(gè)+或-號(hào)。
空格,正數(shù)前加空格,負(fù)數(shù)前加-號(hào)。
,,只用與十進(jìn)制,每3位數(shù)字間用,分隔。
(,若結(jié)果為負(fù)數(shù),則用括號(hào)括住,且不顯示符號(hào)。
可用轉(zhuǎn)換符:
b,布爾類型,只要實(shí)參為非false的布爾類型,均格式化為字符串true,否則為字符串false。
n,平臺(tái)獨(dú)立的換行符, 也可通過System.getProperty("line.separator")獲取。
f,浮點(diǎn)數(shù)型(十進(jìn)制)。顯示9位有效數(shù)字,且會(huì)進(jìn)行四舍五入。如99.99。
a,浮點(diǎn)數(shù)型(十六進(jìn)制)。
e,指數(shù)類型。如9.38e+5。
g,浮點(diǎn)數(shù)型(比%f,%a長(zhǎng)度短些,顯示6位有效數(shù)字,且會(huì)進(jìn)行四舍五入)
總結(jié)
以上就是Java中保留兩位小數(shù)多種寫法的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。