java保留小数位,常用三种方法!!!

    科技2025-06-25  12

    java保留小数位,常用三种方法!!!

    1.java.text.DecimalFormat2.String .format("%.2f",sum)3.BigDecimal

    1.java.text.DecimalFormat

    java.text.DecimalFormat df =new java.text.DecimalFormat("#.00"); df.format(你要格式化的数字);

    例:new java.text.DecimalFormat("#.00").format(3.1415926) 结果为3.14

    #.00 表示两位小数, #.0000四位小数 以此类推…

    这里只要改变index的值便可以得到想要的位数

    int x=sc.nextInt(); int y=sc.nextInt(); int z=sc.nextInt(); double x1=sc.nextDouble(); double y1=sc.nextDouble(); double z1=sc.nextDouble(); int index=sc.nextInt(); double sum=0; sum=x1/x+y1/y+z1/z; String weishu="#."; while(index>0) { weishu+="0"; index--; } System.out.println(new java.text.DecimalFormat(weishu).format(sum));

    2.String .format("%.2f",sum)

    “%.2f” 表示保留两位小数,sum是你传入的值 同样的下面代码你只要改变index的值,便可以得到想要的位数

    int x=sc.nextInt(); int y=sc.nextInt(); int z=sc.nextInt(); double x1=sc.nextDouble(); double y1=sc.nextDouble(); double z1=sc.nextDouble(); int index=sc.nextInt(); double sum=0; sum=x1/x+y1/y+z1/z; System.out.println(String.format("%."+index+"f",sum));

    3.BigDecimal

    使用BigDecimal对象的 setScale() 方法进行格式化 index表示小数的位数

    int x=sc.nextInt(); int y=sc.nextInt(); int z=sc.nextInt(); double x1=sc.nextDouble(); double y1=sc.nextDouble(); double z1=sc.nextDouble(); int index=sc.nextInt();//保留几位数 double sum=0; sum=x1/x+y1/y+z1/z; BigDecimal bd = new BigDecimal(sum); System.out.println(bd.setScale(index, RoundingMode.HALF_UP));
    Processed: 0.010, SQL: 8