数值类型的保留指定小数位

搜集了有如下几种方式:

1、将double类型强制先乘10的n次位然后再转换成int类型

1      double b1=12.354;
2         float b2=((int)(b1*100))/100.0f;//这里可以用float,也可以用double,使用int类型将小数去掉
3 //      double b2=((int)(b1*100))/100.0;
4         System.out.println(String.format("%.2f",b2));

2、使用Math的floor或者ceil方法

     double b3=11.56;
        double floor =( Math.floor(b3*10))/10.0;
        System.out.println(floor);//返回11.5
//        System.out.println(Math.floor(11.5));//返回11
//        System.out.println(Math.ceil(11.5));//返回12

3、使用String的format方法

 1 System.out.println(String.format("%.2f",123.456));//返回123.46 

4、使用Math的round方法

1 float   a   =   123.2334f;  
2 System.out.println((float)Math.round(a*100)/100);

5、利用 BigDecimal类和DecimalFormat的构造方法

1  //第三种
2          String str ="23423.12528";
3          BigDecimal b = new BigDecimal(str);
4 //         DecimalFormat d1 =new DecimalFormat("#,##0.####;(#)");
5          DecimalFormat d1 =new DecimalFormat("#.00");//用于输出两位小数,也可以用#.##,会达到同样的效果
6            System.out.println(d1.format(b));//输出23423.13

猜你喜欢

转载自www.cnblogs.com/jincheng81/p/9028215.html