Double、float类型精确到小数点后几位

Double、float类型精确到小数点后几位

原创  2016年12月01日 09:34:23

需求:返回的一系列数据,精确到小数点后2位


方法一、使用Math.round()

Double value = 0.254668;

(double)Math.round(value*100)/100


方法二、使用DecimalFormat方法

DecimalFormat format=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        String p=format.format(value);//format 返回的是字符串



我当前的需求是计算两个坐标的距离,小于1000米显示米,大于一公里显示公里

    double distance = .....;

      if(distance>1000){

//方法一
                DecimalFormat format=new DecimalFormat(".0");//不足1位,会以0补足.
                String v=format.format(distance/1000);
                Log.i("distance", "DecimalFormat: "+v+"公里");

//方法二
                double a  =(double)Math.round(distance/100)/10;
                Log.i("distance", "Math.round: "+a+"公里");
     }else{
                Log.i("distance", "markPoint: "+(int)distance+"米");
     }


需求:返回的一系列数据,精确到小数点后2位


方法一、使用Math.round()

Double value = 0.254668;

(double)Math.round(value*100)/100


方法二、使用DecimalFormat方法

DecimalFormat format=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        String p=format.format(value);//format 返回的是字符串



我当前的需求是计算两个坐标的距离,小于1000米显示米,大于一公里显示公里

    double distance = .....;

      if(distance>1000){

//方法一
                DecimalFormat format=new DecimalFormat(".0");//不足1位,会以0补足.
                String v=format.format(distance/1000);
                Log.i("distance", "DecimalFormat: "+v+"公里");

//方法二
                double a  =(double)Math.round(distance/100)/10;
                Log.i("distance", "Math.round: "+a+"公里");
     }else{
                Log.i("distance", "markPoint: "+(int)distance+"米");
     }


猜你喜欢

转载自blog.csdn.net/evilcry2012/article/details/79903598