JAva四捨五入方法

1129 ワード

詳細
  public static void main(String[] args) {   
        // 1.        ,   ;   
        double d = 62.31060027198647;   
  
        double d2 = Math.round(d*100)/100.0;   
        System.out.println("  Math      : " + d2);   
  
        // 2.   BigDecimal setScale()              ,       BigDecimal  .   
        BigDecimal bd = new BigDecimal(d);   
        BigDecimal bd2 = bd.setScale(2, BigDecimal.ROUND_HALF_UP);   
        System.out.println("  BigDecimal.setScale  : " + bd2);   
  
        // 3.   DecimalFormat.format  String    
        DecimalFormat df = new DecimalFormat("#.##");   
        System.out.println("  DecimalFormat.format  : " + df.format(d));   
  
        // 4.   String.format   
        System.out.println("  StringFormat: " + String.format("%.2f", d));   
    }   
  
//   Math      : 62.31   
//   BigDecimal.setScale  : 62.31   
//   DecimalFormat.format  : 62.31   
//   StringFormat: 62.31