我可以用system。out。print吗?


当前回答

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

其他回答

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

还要注意NumberFormatException

float f = 102.236569f; 
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f)); // output is 102.24

试试这个:

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


 }

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

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

float myFloat = 2.001f;

String formattedString = String.format("%.02f", myFloat);
float floatValue=22.34555f;
System.out.print(String.format("%.2f", floatValue));

输出是22.35。 如果需要3个小数点,则将其更改为“%.3f”。