如何在Java中打印2位小数的浮点数? [英] How to print a float with 2 decimal places in Java?

查看:24
本文介绍了如何在Java中打印2位小数的浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以用 System.out.print 做吗?

推荐答案

您可以使用 printf 方法,像这样:

You can use the printf method, like so:

System.out.printf("%.2f", val);

简而言之,%.2f 语法告诉 Java 返回带有 2 个小数位 (.2) 的变量 (val)从格式说明符 (%) 开始的浮点数 (f) 的十进制表示.

In short, the %.2f syntax tells Java to return your variable (val) with 2 decimal places (.2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).

除了 f 之外,您还可以使用其他转换字符:

There are other conversion characters you can use besides f:

  • d:十进制整数
  • o:八进制整数
  • e:科学记数法中的浮点数
  • d: decimal integer
  • o: octal integer
  • e: floating-point in scientific notation

这篇关于如何在Java中打印2位小数的浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆