我可以用system。out。print吗?


当前回答

试试这个:

private static String getDecimalFormat(double value) {

    String getValue = String.valueOf(value).split("[.]")[1];

      if (getValue.length() == 1) {
          return String.valueOf(value).split("[.]")[0] +
                "."+ getValue.substring(0, 1) + 
                String.format("%0"+1+"d", 0);
       } else {
          return String.valueOf(value).split("[.]")[0]
            +"." + getValue.substring(0, 2);
      }


 }

其他回答

很多人都提到过DecimalFormat。但是如果你有最新版本的Java,你也可以使用printf:

System.out.printf("%1.2f", 3.14159D);

有关printf格式字符串的更多信息,请参阅Formatter上的文档。

看看DecimalFormat

下面是教程中的一个例子:

  DecimalFormat myFormatter = new DecimalFormat(pattern);
  String output = myFormatter.format(value);
  System.out.println(value + "  " + pattern + "  " + output);

如果你选择像“###”这样的图案。##”,你会得到两位小数点后,我认为值是四舍五入。你会想要查看链接以获得你想要的确切格式(例如,你是否想要后面的零)

在Java中输出小数点后2位的浮点数:

    float f = (float)11/3;
    System.out.print(String.format("%.2f",f));

输出:3.67

>使用%。3f表示小数点后三位。

你可以使用下面的快速代码,它在最后改变了自己。加上这个点后面有多少个0

float y1 = 0.123456789;
DecimalFormat df = new DecimalFormat("#.00");  
y1 = Float.valueOf(df.format(y1));

变量y1之前等于0.123456789。在代码之后,它只会变成0.12。

double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));