I am trying to get the program's decimal to output in two decimal places after the decimal. Please advise.

// MilesPerGallon.java
// Program designed by XY
 
   import javax.swing.JOptionPane; // Needed for JOptionPane.

   import java.text.DecimalFormat; // Keeping proper decimal format.

  
   public class MilesPerGallon
   {
      public static void main(String args[])
      {
         double miles_driven;			// amount of miles driven
         double GallonsOfGas; 			// gallons of gas used
         String input;				// hold user's input
         double MPG;				// miles per gallon			
      
      				
      	// Create a DecimalFormat object.
      	
         DecimalFormat dec = new DecimalFormat("###.##");
      	
      	
      	// Get the number of miles driven from user.
      
         input = JOptionPane.showInputDialog("Enter the number of miles that you have driven. ");
         miles_driven = Double.parseDouble(input); // converts the string into a numeric value.
      
      	      
      	// Get the number of gallons of Gas used from user.	
      
         input = JOptionPane.showInputDialog("Enter the number of gallons that you have used. ");
         GallonsOfGas = Double.parseDouble(input); // converts the string into a numeric value.
      
         // Formula for finding the miles-per-gallon.
			

			MPG = miles_driven/GallonsOfGas;	      				
      	      
      	// Display the miles-per-gallon for user.
      
         JOptionPane.showMessageDialog(null, "The miles per gallon is " + MPG);
      
         System.exit(0);
      }
   }

I am trying to get the program's decimal to output in two decimal places after the decimal. Please advise.

You created dec here but you didn't use it anywhere.

DecimalFormat dec = new DecimalFormat("###.##");

There are several ways to do this, but, what you did is good. Try calling it on this line to do your formatting. I would suggest dec.format You should be able to figure out where to put it. Hope this helps.

JOptionPane.showMessageDialog(null, "The miles per gallon is " + MPG);

Gotcha. It took me a while tho.

JOptionPane.showMessageDialog(null, "The miles per gallon is " + dec.format(MPG));

thanks a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.