java double类型保留两位小数4种方法【转】

 1 4种方法,都是四舍五入,例:  
 2   
 3     import java.math.BigDecimal;  
 4     import java.text.DecimalFormat;  
 5     import java.text.NumberFormat;  
 6     public class format {  
 7         double f = 111231.5585;  
 8         public void m1() {  
 9             BigDecimal bg = new BigDecimal(f);  
10             double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();  
11             System.out.println(f1);  
12         }  
13         /** 
14          * DecimalFormat转换最简便 
15          */  
16         public void m2() {  
17             DecimalFormat df = new DecimalFormat("#.00");  
18             System.out.println(df.format(f));  
19         }  
20         /** 
21          * String.format打印最简便 
22          */  
23         public void m3() {  
24             System.out.println(String.format("%.2f", f));  
25         }  
26         public void m4() {  
27             NumberFormat nf = NumberFormat.getNumberInstance();  
28             nf.setMaximumFractionDigits(2);  
29             System.out.println(nf.format(f));  
30         }  
31         public static void main(String[] args) {  
32             format f = new format();  
33             f.m1();  
34             f.m2();  
35             f.m3();  
36             f.m4();  
37         }  
38     }  
39 //还有一种直接向上取整数  
40 <h2 class="title content-title">//java:Java的取整函数</h2>    <div id="content" class="content mod-cs-content text-content clearfix"> //Math.floor()、Math.ceil()、BigDecimal都是Java中的取整函数,但返回值却不一样  
41               
42             Math.floor()  
43             通过该函数计算后的返回值是舍去小数点后的数值  
44             如:Math.floor(3.2)返回3  
45             Math.floor(3.9)返回3  
46             Math.floor(3.0)返回3  
47               
48             Math.ceil()  
49             ceil函数只要小数点非0,将返回整数部分+1  
50             如:Math.ceil(3.2)返回4  
51             Math.ceil(3.9)返回4  
52             Math.ceil(3.0)返回3 </div>  

转自: 

java double类型保留两位小数4种方法

posted @ 2016-06-08 15:47  GoQC  阅读(3938)  评论(0编辑  收藏  举报