Home > Enterprise >  How to format a String using 3 parameters in Java
How to format a String using 3 parameters in Java

Time:01-30

I have two classes, one where I create a format method that will format a String output by its width (length of the output string), by its places (the number of places after the decimal points), and by the value that I am looking to format. The other class has a method to print out values using the format method. I tried to figure out how to do this myself, but I am getting errors and am not getting the output I am looking for. I am a super beginner using Java for context.

The method I am struggling with:

  /**
    * Creates a String representation of the given double value.
    * @param value  The double value to be formatted
    * @param places The number of places after the decimal point
    * @param width  The length of the output String. The value will be
    *               right justified within the output String.
    * @return str   The formatted string
    */

   public static String format(double value, int places, int width) {

      // how do I format using the parameters places and width?
     String str = String.format("%"   width   ".f"   places, value);

     return str;
      
   }

Part of another class method that will implement the format method:

   // prints out values
     System.out.println(dbl.format(a, places: 1, width: 6)   ""   dbl.format(b, places: 3, width: 12));
  }

CodePudding user response:

It's something like String.format(" .5f"), you are making " .f5". Instead of ".f" places, you want "." places "f".

  • Related