方式一:
1
2
3
4
|
double f = 3.1516 ; BigDecimal b = new BigDecimal(f); double f1 = b.setScale( 2 , BigDecimal.ROUND_HALF_UP).doubleValue(); 輸出結果f1為 3.15 ; |
源碼解讀:
public BigDecimal setScale(int newScale, int roundingMode) //int newScale 為小數點后保留的位數, int roundingMode 為變量進行取舍的方式;
BigDecimal.ROUND_HALF_UP 屬性含義為為四舍五入
方式二:
1
2
3
|
String format = new DecimalFormat( "#.0000" ).format( 3.1415926 ); System.out.println(format); 輸出結果為 3.1416 |
解讀:
#.00 表示兩位小數 #.0000四位小數 以此類推…
方式三:
1
2
3
4
|
double num = 3.1415926 ; String result = String.format( "%.4f" , num); System.out.println(result); 輸出結果為: 3.1416 |
解讀:
%.2f 中 %. 表示 小數點前任意位數 2 表示兩位小數 格式后的結果為f 表示浮點型。
方式四:
1
2
3
|
double num = Math.round( 5.2544555 * 100 ) * 0 .01d; System.out.println(num); 輸出結果為: 5.25 |
解讀:
最后乘積的0.01d表示小數點后保留的位數(四舍五入),0.0001 為小數點后保留4位,以此類推......
方式五:
1. 功能
將程序中的double值精確到小數點后兩位。可以四舍五入,也可以直接截斷。
比如:輸入12345.6789,輸出可以是12345.68也可以是12345.67。至于是否需要四舍五入,可以通過參數來決定(RoundingMode.UP/RoundingMode.DOWN等參數)。
2. 實現代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
package com.clzhang.sample; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.NumberFormat; public class DoubleTest { /** 保留兩位小數,四舍五入的一個老土的方法 */ public static double formatDouble1( double d) { return ( double )Math.round(d* 100 )/ 100 ; } public static double formatDouble2( double d) { // 舊方法,已經不再推薦使用 // BigDecimal bg = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP); // 新方法,如果不需要四舍五入,可以使用RoundingMode.DOWN BigDecimal bg = new BigDecimal(d).setScale( 2 , RoundingMode.UP); return bg.doubleValue(); } public static String formatDouble3( double d) { NumberFormat nf = NumberFormat.getNumberInstance(); // 保留兩位小數 nf.setMaximumFractionDigits( 2 ); // 如果不需要四舍五入,可以使用RoundingMode.DOWN nf.setRoundingMode(RoundingMode.UP); return nf.format(d); } /**這個方法挺簡單的 */ public static String formatDouble4( double d) { DecimalFormat df = new DecimalFormat( "#.00" ); return df.format(d); } /**如果只是用于程序中的格式化數值然后輸出,那么這個方法還是挺方便的, 應該是這樣使用:System.out.println(String.format("%.2f", d));*/ public static String formatDouble5( double d) { return String.format( "%.2f" , d); } public static void main(String[] args) { double d = 12345.67890 ; System.out.println(formatDouble1(d)); System.out.println(formatDouble2(d)); System.out.println(formatDouble3(d)); System.out.println(formatDouble4(d)); System.out.println(formatDouble5(d)); } } |
3. 輸出
12345.68
12345.68
12,345.68
12345.68
12345.68
以上就是Java四舍五入時保留指定小數位數的五種方式的詳細內容,更多關于Java四舍五入時保留指定小數位數的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/yysbolg/p/11095548.html