Java输出多位小数(三种方法)


方法一:String类的方式

最常用的方式:
image.png

double a=3.141111;
System.out.println(String.format("%.1f",a));//保留一位小数
System.out.println(String.format("%.2f",a));//保留两位小数
System.out.println(String.format("%.3f",a));//保留三位小数
System.out.print(String.format("%.4f",a));//用print可以取消换行

方法二:printf格式化输出

与C语言相似,Java中也可以通过printf输出:
image.png

double a=3.141111;
System.out.printf("%.1f",a);//保留一位小数
System.out.printf("%.2f",a);//保留两位小数
System.out.printf("%.3f",a);//保留三位小数
System.out.printf("%.4f\n",a);//加\n可以换行

方法三:DecimalFormat类的方式

DecimalFormat 是 NumberFormat 的一个具体子类,用于格式化十进制数字,主要靠0和#两个占位符号。
#表示如果尽可能占需占的位数。
0表示如果位数不足则用0补足。
image.png

//class前=导入:
import java.text.DecimalFormat;
//#的使用:
DecimalFormat a = new DecimalFormat("#.#");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("#.#");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("##.##");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("###.###");
System.out.println(a.format(12.34)); //打印12.34

可以看出,#好像并没有什么作用,该打印什么就打印什么,但并不是这样的,它是与大多与0一起使用,起着很大的作用。

//0的使用:
DecimalFormat a = new DecimalFormat("0.0");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("00.00");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("000.000");
System.out.println(a.format(12.34)); //打印012.340
//#和0的使用
DecimalFormat a = new DecimalFormat("#.#");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("#.#");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("##.##");
System.out.println(a.format(12.34)); //打印12.34

举例(完整代码):

import java.text.DecimalFormat;
public class Test {
    
    
    public static void main(String[] args) {
    
    
        DecimalFormat a = new DecimalFormat("#.00");
        System.out.println(a.format(12.34567)); //四舍五入输出12.35
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_74837727/article/details/130090751
今日推荐