Format a Double number at 2 decimals when printing in Java -


here code:

public static void main (string[] args) {     //greeting , explanation of program     scanner keyboard = new scanner(system.in);      system.out.print("i going keep track of fuel consumption "             + "by converting metric system miles , gallons.\n");      system.out.print("how many kilometers have 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 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 car getting " + milepergallon +             " miles per gallon.");  } 

one last line supposed have mpg rounded 2 decimal places. not sure how this. heard supposed add %.2f in there somewhere, don't know where.

since string.format can use:

string.format("%02d", yournumber) 

or doing like:

system.out.printf("so car getting %02d miles per gallon.", milepergallon); 

Comments