Luke8h
Luke8h

Reputation: 13

Format a Double number at 2 decimals when printing in Java

Here is my code:

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.");

}

One the last line I am supposed to have the MPG rounded to two decimal places. I am not sure how to do this. I heard that I am supposed to add %.2f in there somewhere, but don't know where.

Upvotes: 0

Views: 300

Answers (1)

Since string.format you can use:

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

or just doing like:

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

Upvotes: 1

Related Questions