我可以用system。out。print吗?


当前回答

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

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

float myFloat = 2.001f;

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

其他回答

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

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

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

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

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

float myFloat = 2.001f;

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

还要注意NumberFormatException

你可以使用DecimalFormat。有一种用法:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));

另一种方法是使用#来构造它。# #格式。

我发现所有格式化选项的可读性都不如调用格式化方法,但这是个人偏好的问题。

试试这个:

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);
      }


 }