4

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

Abdul Alim Shakir
  • 1,128
  • 13
  • 26

2 Answers2

5

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".

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 1
    Also, it is worth noting that %.2f also performs round-off, in case if the number exceeds 2 decimal places. And, $%07.2f also makes sure if the number is more than 5 characters in length, it does not truncate the non-decimal part. So, Need not always be resulting in 7 chars, Just in case! – Mohamed Anees A Sep 09 '19 at 06:14
0

This will give you exactly what you want:

double num = 105.456789;
System.out.println(String.format("Gross Pay:     $%04.0f", num) +
        "." + String.valueOf(num).split("\\.")[1].substring(0,2));

Output:

Gross Pay:     $0105.45

Explanation: As far as I know you can't take the 2 digits after the point with String.format without rounding (please correct me if I'm wrong), so I suggest using the split method. If you want you can cram this all into one statement like I did but it isn't very pretty so its up to you.

Ed B
  • 23
  • 4