这是我的代码:

public static void main (String[] args)
{
    //Greeting and explanation of program
    Scanner keyboard = new Scanner(System.in);

    System.out.print("I am going to help you keep track of fuel consumption "
            + "by converting the metric system into miles and gallons.\n");

    System.out.print("How many kilometers have you driven?\n");
    double kilometers =keyboard.nextDouble();

    double milePerKilometer = Math.round(kilometers/1.609);

    System.out.printf("You drove: "+ milePerKilometer + " miles.\n\n");

    System.out.print("How many liters of gas have you purchased?\n");
    double liters = keyboard.nextDouble();

    double gallonPerLiter = Math.round(liters/3.785);

    System.out.printf("You purchased: "+ gallonPerLiter + " gallons of gas.\n\n");

    double milePerGallon = (milePerKilometer/gallonPerLiter);

    System.out.printf("So your car is getting " + milePerGallon +
            " miles per gallon.");

}


我应该把MPG的最后一行取整到小数点后两位。我不确定该怎么做。我听说应该在其中添加%.2f,但不知道在哪里。

最佳答案

从string.format开始,您可以使用:

String.format("%02d", yourNumber)


或只是这样做:

System.out.printf("So your car is getting %02d miles per gallon.", milePerGallon);

关于java - 在Java中打印时,将两位数字格式化为两位小数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34977993/

10-12 04:20