如何在Java中显示2位小数的float数据输出? [英] How to display an output of float data with 2 decimal places in Java?

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

问题描述

我可以用 System.out.print

解决方案

来完成。您可以使用 printf 方法,如下所示:

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

总之,%。2f 语法告诉Java以浮点数的十进制表示形式返回带有2个小数位( .2 )的变量( val 从格式说明符()开头的点号( f )。



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


  • d :十进制整数
  • o :八进制整数
  • li>
  • e :科学记数法中的浮点数


你可以在学习中看到一些例子Java - 第5章


Can I do it with System.out.print?

解决方案

You can use the printf method, like so:

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

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 (%).

There are other conversion characters you can use besides f:

  • d: decimal integer
  • o: octal integer
  • e: floating-point in scientific notation

You can see some examples at Learning Java - Chapter 5

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

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