Java处理小数点位数

以取小数点两位为例

import java.math.BigDecimal;
import java.text.NumberFormat;

public class Demo01 {
    public static void main(String[] args) {
        //方法一
        double   f   =   111.57878;
        BigDecimal b   =   new   BigDecimal(f);
        double   f1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();//BigDecimal.ROUND_DOWN不四舍五入
        System.out.println(f1);
        //方法二
        java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");
        double x =111.57878;
        System.out.println(df.format(x));
        //方法三
        double d = 111.57878;
        String result = String .format("%.2f",d);
        System.out.println(result);
        //方法四
        double y=111.57878;
        NumberFormat ddf1= NumberFormat.getNumberInstance() ;
        ddf1.setMaximumFractionDigits(2);
        String s= ddf1.format(y) ;
        System.out.print(s);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44168355/article/details/89885073