在 java 中显示带 2 位的输出小数

Displaying an output decimal with 2 places in java

我试图找出为什么输出小数时的 %.2f 声明在我的代码中不起作用,我已经检查了其他类似的问题,但我似乎无法在我收到的具体逻辑错误。当我去编译我的程序时,它编译得很好,我转到 运行 它并且一切输出都很好,直到我得到最终成本,我试图只显示小数点后两位小数。

我在线程中遇到异常 "main"

Java.util.illegalformatconversionexception  f! = Java.lang.string
At java.util.Formatter$formatspecifier.failconversion(Unknown Source)
At java.util.Formatter$formatspecifier.printFloat(Unknown Source)
At java.util.Formatter.format(Unknown Source)
At java.io.printstream.format(Unknown Source)
At java.io.printstream.printf(Unknown Source)
At Cars.main(Cars.java:27)

这是我的代码:

import java.util.Scanner;
public class Cars
{

  public static void main(String [] args)
  {
    Scanner input = new Scanner(System.in);

    int carYear, currentYear, carAge;

    double costOfCar, salesTaxRate;
    double totalCost;

    String carModel;
    System.out.println("Please enter your favorite car model.");
        carModel = input.nextLine();
    System.out.println("Please enter the  year of the car");
        carYear = input.nextInt();
    System.out.println("Please enter the current year.");
        currentYear = input.nextInt();
        carAge = currentYear - carYear;
    System.out.println("How much does the car cost?");
        costOfCar = input.nextDouble();
    System.out.println("What is the sales tax rate?");
        salesTaxRate = input.nextDouble();
        totalCost = (costOfCar + (costOfCar * salesTaxRate));
    System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f",totalCost + " " + " dollars."); 

    }
}

我不确定是什么导致了这个问题。

尝试:

System.out.printf("The model of your favorite car is %s, the car is %d years old, the total of the car is %.2f dollars.", carModel, carAge, totalCost);

或者更具可读性:

System.out.printf("The model of your favorite car is %s," +
                  " the car is %d years old," +
                  " the total of the car is %.2f dollars.",
                  carModel, carAge, totalCost);

这是因为 %.2f 在该方法调用中被替换为整个第二个参数。问题在于,通过在 %.2f 中指定 f,您表示第二个参数是浮点数或双精度数。本例中的第二个参数是 totalCost + " " + " dollars.",它的计算结果是一个字符串。

要解决此问题,您需要将第二个参数设置为浮点数或双精度数。这可以通过将 + " " + " dollars." 从第二个参数的末尾移动到第一个参数的末尾来实现,如下所示:

System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f" + " " + " dollars.",totalCost);

您还可以从该行中删除许多不必要的连接,结果如下:

System.out.printf("The model of your favorite car is" + carModel + ", the car is " + carAge + " years old, the total of the car is %.2f dollars.", totalCost);

变量必须作为 System.out.printf() 函数的参数。 “%.2f”将替换为作为第二个参数传递的双精度值。

例如:

    System.out.printf("The value is %.2f", value);

其他变量类型和多变量也是如此,

    String str = "The value is: ";
    double value = .568;
    System.out.printf("%s %.2f", str, value);

这将输出:"The value is: .57"