在Java中打印时,格式化为2位小数的双精度数

时间:2016-01-24 16:05:05

标签: java decimal

这是我的代码:

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 ,但不知道在哪里。

1 个答案:

答案 0 :(得分:1)

因为string.format你可以使用:

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

或者只是这样做:

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