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
    }
}
  • 23
    点赞
  • 92
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值