Search code examples
javastringdecimalstring-formatting

How to format a string so that it prints 4 digits and 2 decimals


I am trying to print out a double that is always 4 digits as well as has 2 decimal places.

For example, If the number was 105.456789 my String.Format would print out 0105.45 I understand that %.2f allows for the two decimal place problem. I also understand that %04d allows for the 4 digit problem However, I cannot for the life of me figure out how to combine the two.

I have tried doing a double String.format I have tried doing one String.format and using both %04d and %.2f

System.out.println(String.format("Gross Pay:     $%.2f %04d", 105.456789));

I expect the output to be 0105.45 but I can't even get it to compile


Solution

  • Two things: first of all, your code does compile. But it immediately fails at runtime:

    Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%04d'

    Because: you are using two patterns in your format spec, but provide only one value.

    Yes, %.2f %04d that are two specs, not one.

    ( Please let that sink in: there is a distinct difference between compile time errors and runtime exceptions. And it is important to understand that difference. )

    Back to the "real" problem. Instead of using two patterns for one value, you have to thus use one spec, like:

    System.out.println(String.format("Gross Pay:     $%07.2f", 105.456789));
    

    Gross Pay: $0105.46

    The "trick": that number in front of the "dot" needs to account for the overall desired length. Overall, you want: 4 digits+dot+2 digits, resulting in 7 chars. And 0 to fill upfront.

    Thus your spec needs to start with "07".