在Java中打印带有2个小数位的整数

use*_*458 13 java format number-formatting output

在我的代码中,我使用整数乘以100作为小数(0.1是10等).你能帮我格式化输出以显示为十进制吗?

Juv*_*nis 28

int x = 100;
DecimalFormat df = new DecimalFormat("#.00"); // Set your desired format here.
System.out.println(df.format(x/100.0));
Run Code Online (Sandbox Code Playgroud)


Yog*_*ngh 10

我会说要0.00用作格式:

      int myNumber = 10;
      DecimalFormat format = new DecimalFormat("0.00"); 
      System.out.println(format.format(myNumber));
Run Code Online (Sandbox Code Playgroud)

它将打印如下:           

      10.00
Run Code Online (Sandbox Code Playgroud)

这里的优点是:

如果你喜欢:

      double myNumber = .1;
      DecimalFormat format = new DecimalFormat("0.00"); 
      System.out.println(format.format(myNumber));
Run Code Online (Sandbox Code Playgroud)

它将打印如下:

      0.10
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 5

您可以通过除以它们的因子(作为双精度)打印出编码为整数的十进制数

int i = 10; // represents 0.10
System.out.println(i / 100.0);
Run Code Online (Sandbox Code Playgroud)

版画

0.1
Run Code Online (Sandbox Code Playgroud)

如果您需要始终显示两个小数位,您可以使用

System.out.printf("%.2f", i / 100.0);
Run Code Online (Sandbox Code Playgroud)