我可以用system。out。print吗?


当前回答

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

用于演示的简单小程序:

import java.io.*;
import java.util.Scanner;

public class twovalues {

    public static void main(String args[]) {

        float a,b;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter Values For Calculation");

        a=sc.nextFloat();
        b=sc.nextFloat();

        float c=a/b;
        System.out.printf("%.2f",c);
    }
}

试试这个:

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


 }

你可以使用printf方法,像这样:

System.out.printf("%.2f", val);

简而言之,%。2f语法告诉Java从格式说明符(%)开始以浮点数(f)的十进制表示形式返回变量(val),其中有2位小数(.2)。

除了f,你还可以使用其他转换字符:

D:十进制整数 O:八进制整数 E:科学记数法中的浮点数