Java保留小数点后几位的几种方法

文章介绍了在Java编程中,如何使用DecimalFormat类,String.format()方法以及System.out.printf()来保留小数点后的指定位数。通过示例代码展示了不同方法的用法,包括四舍五入、不足位用0填充等规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java保留小数点后几位的几种写法

常用解决方法:
1,使用DecimalFormat类;
2,使用String.format()
3,使用System.out.printf()

实例代码如下:

        DecimalFormat df = new DecimalFormat("0.00");
        double a = 0.7854213;
        double b = 0.7;
        int c = 1;
        int d = 12564;
        System.out.println(df.format(a));   // 0.79 遵循四舍五入原则
        System.out.println(df.format(b));   // 0.70 没有的位会用0补全


        DecimalFormat df1 = new DecimalFormat("#.###");
        System.out.println(df1.format(a));   // 0.785 遵循四舍五入原则
        System.out.println(df1.format(b));  // 0.7 没有的位不会补全

        DecimalFormat df2 = new DecimalFormat("000");
        System.out.println(df2.format(c));    // 001  输出固定格式的,不够位的用前导0补全
        System.out.println(df2.format(d));    // 12564 超出位的也不会做切割,原样输出

        String s = String.format("%.2f",a);   // 0.79 遵循四舍五入原则
        System.out.println(s);
        String s1 = String.format("%.2f",b);   // 0.70 不够的位用0补全
        System.out.println(s1);
        String s2 = String.format("%03d", c);   // 001
        System.out.println(s2);
        String s3 = String.format("%03d", d);    // 12564 超过位则原样输出
        System.out.println(s3);

        // 只输出保留两位小数
        System.out.printf("%.2f", a);   // 0.79 遵循四舍五入原则

参考:关于 Java 小数点位数保留的解决方案

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值