1

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));
  }

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.