java小数与保留位

// 方式一:
double f = 3.1516;
BigDecimal b = new BigDecimal(f);
double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
 
// 方式二:
new java.text.DecimalFormat("#.00").format(3.1415926);
// #.00 表示两位小数 #.0000四位小数 以此类推…
 
// 方式三:
double d = 3.1415926;
String result = String.format("%.2f", d);
// %.2f %. 表示 小数点前任意位数 2 表示两位小数 格式后的结果为f 表示浮点型。
 
//方法四:
Math.round(5.2644555 * 100) * 0.01d;
//String.format("%0" + 15 + "d", 23) 23不足15为就在前面补0
import java.text.DecimalFormat;  

public class Hello {  
    public static void main(String args[])  
    {     
        //double d = 1.2345;    输出1.234
     float d=1.2345; //这个方法只对float类型的四舍五入有效 输出1.235 System.out.println(d);     DecimalFormat df
= new DecimalFormat("#.###"); System.out.println(df.format(d)); } }

对于double

  public class Hello {
    public static double numberWithPrecision(double value, int precision) {
        double temp = Math.pow(10, precision);
        return ((int) Math.round(temp * value)) / temp;
      }

    public static void main(String[] args) {
        System.out.println(Hello.numberWithPrecision(6.615, 2));
      }
  }

  

  double d = 3.1415926;
  String result = String.format("%.3f", d);   
  System.out.println(result);  //输出3.142

 

 

posted @ 2015-05-13 10:39  Maydow  阅读(152)  评论(0编辑  收藏  举报