我可以用system。out。print吗?


当前回答

你可以使用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);
      }


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

还要注意NumberFormatException

一个简单的技巧是生成一个更短的变量,将其与100相乘,四舍五入,然后再除以100.0。这样你就生成了一个小数点后2位的变量:

double new_variable = Math.round(old_variable*100) / 100.0;

这个“廉价的技巧”对我来说已经足够好了,并且适用于任何语言(我不是Java人,只是学习它)。

用str来浮动。

package test;

import java.text.DecimalFormat;

public class TestPtz {
  public static void main(String[] args) {
    String preset0 = "0.09,0.20,0.09,0.07";
    String[] thisto = preset0.split(",");    
    float a = (Float.valueOf(thisto[0])).floatValue();
    System.out.println("[Original]: " + a);   
    a = (float) (a + 0.01);

    // Part 1 - for display / debug
    System.out.printf("[Local]: %.2f \n", a);
    // Part 2 - when value requires to be send as it is
    DecimalFormat df = new DecimalFormat();
    df.setMinimumFractionDigits(2);
    df.setMaximumFractionDigits(2);
    System.out.println("[Remote]: " + df.format(a));

  }
}

输出:

run:
[Original]: 0.09
[Local]: 0.10 
[Remote]: 0.10
BUILD SUCCESSFUL (total time: 0 seconds)

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

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

输出:3.67

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