保留指定位数小数点的方法(五种)

package feifan;

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class YuoXiaoShuzi {
    public static void main(String[] args) {
        //五种方法   推荐1、2、3种  第一种最简单
        /*1.printf("%.几f",要保留几位小数的原始数据)  最简单的方法
        * 2.Math.round();1:四舍五入取整  即将浮点型取整   2:也可以保留指定小数
        * 3.String.format();1.保留几位小数 2.进制转换
        * 4.NumberFormat();
        * 5.DecimalFormat()
        * */

        double x=3.1415926;
        //1.printf格式化
       // System.out.printf("%.3f",x);//记得双引号

        //  加println 后的输出3.1423?

        //2.Math.round();
      //  为什么有println  printf就不输出了?

        System.out.println(Math.round(x*1000)/1000.0);//保留3位有效数字  Math.roun(数据*两位就100 三位就1000)/两位就100.0 三位就1000.0
        System.out.println(Math.round(x));//保留整数


        //3.String.format();  也是格式化
        System.out.println(String.format("%.3f",x));// 转为浮点型  位数不够时自动补充0
        System.out.println(String.format("%o",5050));//11672  将十进制数转八进制
        System.out.println(String.format("%x",5050));//13ba 将一个十进制数转成十六进制

        //4.NumberFormat();   没必要  太复杂  上面那几种还不够你用吗?
        NumberFormat numberFormat=NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(3);//设置保留3位有效数字
        System.out.println(numberFormat.format(x));

       // 5.DecimalFormat()    没必要  太复杂 需要构造方法创建对象 再用对象调方法
        DecimalFormat decimalFormat=new DecimalFormat("#.000");//保留三位小数
        System.out.println(decimalFormat.format(x));
    }
}
经验分享 程序员 微信小程序 职场和发展