我正在创建一个简单的程序来计算运行汽车的成本。该程序运行良好,但我想看看是否可以获得小数点后 2 位的最终答案。我尝试使用'%8.2f'
的东西,但它说no method could be found for println(string, double)
这是我的代码:
/* Program to calculate the running cost of car */
import java.util.Scanner;
public class RunningCosts {
public static void main(String[] args) {
final int TOTAL_DISTANCE = 100000;
Scanner in = new Scanner(System.in);
System.out.print("Enter the car cost: ");
double carCost = in.nextDouble();
System.out.print("Enter the service cost: ");
double serviceCost = in.nextDouble();
System.out.print("Enter the service interval: ");
double serviceInterval = in.nextDouble();
System.out.print("Enter km per litre: ");
double kmPerLitre = in.nextDouble();
System.out.print("Enter the fuel cost per litre: ");
double fuelCostPerLitre = in.nextDouble();
double serviceTotal = (TOTAL_DISTANCE/serviceInterval) * serviceCost;
System.out.println( "Service Total: " + serviceTotal); //Here
double fuelCost = (TOTAL_DISTANCE/kmPerLitre) * fuelCostPerLitre;
System.out.println( "Fuel Cost: " + fuelCost); //Here
double totalCost = carCost + fuelCost + serviceTotal;
System.out.println( "Estimated Cost: " + totalCost); //And here
}
}
注释的行是我希望格式化为小数点后 2 位的内容
按照@shmosel
建议使用 printf
,或使用String.format
System.out.println( "Service Total: " + String.format("%.2f", serviceTotal));
有关更多使用示例,请参阅此页面。