PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 11, 2022

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

 August 11, 2022     decimal, java, string, string-formatting     No comments   

Issue

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



Answered By - GhostCat
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing