java : 保留小数位数的方法

Ex :


    double a=1.2356;
    //方法1
    double b=(double)Math.round(a*100)/100;  //1.23
    //方法2
    String s1=String.format("%.2f",a);  //1.23
    //方法3
    DecimalFormat df=new DecimalFormat("#.##");
    String s2=df.format(a);  //1.23 //如果a=1.2结果为1.2
    //方法4
    DecimalFormat df2=new DecimalFormat("#.00");
    String s3=df2.format(a);  //1.23 //如果a=1.2结果为1.20
    //方法5
    NumberFormat nf=NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);
    nf.setRoundingMode(RoundingMode.DOWN );//down不四舍五入,up四舍五入
    String s4=nf.format(a);    
    //down  a=1.2356    s4 =1.23 
    //up       a=1.2356    s4 =1.24 

猜你喜欢

转载自blog.csdn.net/qq_42451835/article/details/82799945