简体   繁体   中英

Formatting to 2 decimal places in Java

I keep getting an error when trying to format my output to 2 decimal places. Such as from 5.0 I want 5.00 in java. The code below keeps giving a formatting error.

System.out.printf("%-40s %-6.2f", "Borrowing Fee:  $", borrowingFee + "\n");

I want it to output: Borrowing Fee: $5.00

You can use DecimalFormat. It has many utility functions.

public static String getFormattedAmountWithDecimals(String value){
    String tmpDouble = ""; 
     DecimalFormat formatter = new DecimalFormat("###,###,###.00");

    try {
        tmpDouble = formatter.format(Double.parseDouble(value));
        if(tmpDouble.equalsIgnoreCase(".00")){
            tmpDouble = "0.00";
        }
    }catch(Exception e) {
    //  System.out.println(e.toString());
    }
    return tmpDouble;
}   

Why a so complicated code ?? If you have a float as input, you can do that :

  public static void main(String[] args) {
      float borrowingFee = 5.0F;
      System.out.printf("Borrowing Fee:  $%.2f ", borrowingFee );
    }

It should return Borrowing Fee: $5,00 or Borrowing Fee: $5.00 according to your locale.

Formatted printing is same as C if you have been programming in C . try something like this :

System.out.printf("Borrowing Fee: $%.2f",borrowingFee );

I like referring to the public documentation on the method.

https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

The big take away is the format:

public PrintStream format(String format, Object... args)

So then referring back to your code:

System.out.printf("%-40s %-6.2f", "Borrowing Fee: $", borrowingFee + "\\n");

You are trying to string + string + argument + string. So if you wanted to fix your line of code:

System.out.printf("%-40s %-6.2f", "Borrowing Fee: $ \\n", borrowingFee);

That way it's back to the format of the method String + String + ... + n strings, Arguments

First of all, %s means string, and %f means float number.

System.out.printf("%-40s %-6.2f", "Borrowing Fee: $", borrowingFee + "\\n");

In your case, the 3rd argument, borrowingFee + "\\n" , creates a string, which couldn't match up with %f. Which is why you might get the exception message java.util.IllegalFormatConversionException: f != java.lang.String

Here the IllegalFormatConversionException indicates that f (%f) is incompatible with java.lang.String.

The simple fix is moving the \\n into the 1st argument, since it's the format:

System.out.printf("%-40s %-6.2f\n", "Borrowing Fee:  ", borrowingFee);

Notice that the first argument "%-40s %-6.2f\\n" is the format that creates blanks with %s and %f, and the rest arguments are the fillings for those blanks.


In addition, your 2nd argument, "Borrowing Fee: $" , is promised to be a fixed string. Unless you want a giant space between the colon and the number like Borrowing Fee: 55.00 , you don't need to format it. You can simply do

System.out.printf("Borrowing Fee: %.2f\n", borrowingFee);

or slightly larger space with \\t

System.out.printf("Borrowing Fee:\t %.2f\n", borrowingFee);

printf on docs.oracle.com (java7):

public PrintStream printf(String format , Object... args)

Parameters:

  • format - A format string as described in Format string syntax

  • args - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by The Java™ Virtual Machine Specification. The behaviour on a null argument depends on the conversion.


I intend to explain the function call and the error in your code.

Check Andy's link for details on formatting.

Replace

System.out.printf("%-40s %-6.2f", "Borrowing Fee:  $", borrowingFee + "\n");

with

System.out.printf("%-40s %-6.2f%n", "Borrowing Fee:  $", borrowingFee );

Output:

Borrowing Fee:  $                        5.00  

Explanation:

  1. The format for "Borrowing Fee: $" is %-40s
  2. The format for borrowingFee is %-6.2f
  3. %n is for new line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM