我可以用system。out。print吗?


当前回答

只需执行String str = System.out.printf("%。2 f”,val)。取代 (",", ".");如果你想确保独立于用户的Locale,你将总是得到/显示一个"."作为小数分隔符。这是必须的,如果你不想让你的程序崩溃,如果你以后做一些转换,如float f = float . parsefloat (str);

其他回答

double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
float f = 102.236569f; 
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f)); // output is 102.24

看看DecimalFormat

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

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

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

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

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

试试这个:

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


 }