java 四舍五入

来源:互联网 发布:dnf开挂软件 编辑:程序博客网 时间:2024/04/29 10:42

http://kingschan.iteye.com/blog/1537494

Java代码  收藏代码
  1. 4种方法,都是四舍五入,例:   
  2.   
  3.   
  4. import java.math.BigDecimal;  
  5. import java.text.DecimalFormat;  
  6. import java.text.NumberFormat;  
  7.   
  8.   
  9. public class format {  
  10.     double f = 111231.5585;  
  11.     public void m1() {  
  12.         BigDecimal bg = new BigDecimal(f);  
  13.         double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();  
  14.         System.out.println(f1);  
  15.     }  
  16.     /** 
  17.      * DecimalFormat转换最简便 
  18.      */  
  19.     public void m2() {  
  20.         DecimalFormat df = new DecimalFormat("#.00");  
  21.        System.out.println(df.format(f));  
  22.     }  
  23.     /** 
  24.      * String.format打印最简便 
  25.      */  
  26.     public void m3() {  
  27.         System.out.println(String.format("%.2f", f));  
  28.     }  
  29.     public void m4() {  
  30.         NumberFormat nf = NumberFormat.getNumberInstance();  
  31.         nf.setMaximumFractionDigits(2);  
  32.         System.out.println(nf.format(f));  
  33.     }  
  34.     public static void main(String[] args) {  
  35.         format f = new format();  
  36.         f.m1();  
  37.         f.m2();  
  38.         f.m3();  
  39.         f.m4();  
  40.     }