我可以用system。out。print吗?


当前回答

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

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

输出:3.67

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

其他回答

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

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

输出:3.67

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

看看DecimalFormat

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

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

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

我建议使用String.format()如果你需要值作为字符串在你的代码。

例如,你可以这样使用String.format():

float myFloat = 2.001f;

String formattedString = String.format("%.02f", myFloat);

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

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

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

public String getDecimalNumber(String number) {
        Double d=Double.parseDouble(number);
        return String.format("%.5f", d);
}

还要注意NumberFormatException