double类型四舍五入保留两位小数

  1. public class DoubleFormat {  
  2.   
  3.      double f = 111231.4585;    
  4.      public void m1() {    
  5.          BigDecimal bg = new BigDecimal(f);    
  6.          double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();    
  7.          System.out.println(f1);    
  8.      }    
  9.      /**  
  10.       * DecimalFormat转换最简便  
  11.       */    
  12.      public void m2() {    
  13.          //#.00 表示两位小数  
  14.          DecimalFormat df = new DecimalFormat("#0.00");    
  15.          System.out.println(df.format(f));    
  16.      }    
  17.        
  18.      /**  
  19.       * String.format打印最简便  
  20.       */    
  21.      public void m3() {    
  22.          //%.2f  %.表示 小数点前任意位数   2 表示两位小数 格式后的结果为f 表示浮点型  
  23.          System.out.println(String.format("%.2f", f));    
  24.      }    
  25.        
  26.      public void m4() {    
  27.           
  28.          NumberFormat nf = NumberFormat.getNumberInstance();    
  29.          //digits 显示的数字位数 为格式化对象设定小数点后的显示的最多位,显示的最后位是舍入的  
  30.          nf.setMaximumFractionDigits(2);    
  31.          System.out.println(nf.format(f));    
  32.      }   
  33.        
  34.      public static void main(String[] args) {    
  35.          DoubleFormat f = new DoubleFormat();    
  36.          f.m1();    
  37.          f.m2();    
  38.          f.m3();    
  39.          f.m4();    
  40.      }    
  41.        
  42.        
  43.      //还有一种直接向上取整数    
  44.    //java:Java的取整函数  
  45.   
  46.    //Math.floor()、Math.ceil()、BigDecimal都是Java中的取整函数,但返回值却不一样    
  47.                 
  48.     /*        Math.floor()  通过该函数计算后的返回值是舍去小数点后的数值   
  49.             如:Math.floor(3.2)返回3   
  50.             Math.floor(3.9)返回3   
  51.             Math.floor(3.0)返回3   
  52.                
  53.             Math.ceil()   
  54.             ceil函数只要小数点非0,将返回整数部分+1   
  55.             如:Math.ceil(3.2)返回4   
  56.             Math.ceil(3.9)返回4   
  57.             Math.ceil(3.0)返回3*/  
  58.               
  59.  }    

猜你喜欢

转载自blog.csdn.net/weixin_41703383/article/details/80117999