I am using DecimalFormat to create a formated decimal that is always 6 characters long. At first I used the format string of new DecimalFormat("000.00")
but this gave me a bug for negative numbers. The minus sign is added and makes the number one space larger resulting in -005.25
and not -05.25
as desired.
I have been able to fix this with the following code
DecimalFormat fmt;
if(netAmt < 0){
fmt = new DecimalFormat("00.00");
}else{
fmt = new DecimalFormat("000.00");
}
System.out.println(fmt.format(netAmt));
But DecimalFormat has the ;
character to format negative numbers differently then positive numbers. I have not been able to get this work correctly. As I understand it the following code should work just like the above.
DecimalFormat fmt = new DecimalFormat("000.00;00.00");
System.out.println(fmt.format(netAmt));
The result is that the pattern before the ;
is used for both negative and positive numbers causing the -005.25
error to remain. What am I doing wrong? Am I misunderstanding what ;
is for?
Does the following string pattern help you:
"%06.2f%n"
A fixed width of 6 with "0" padding the front?example
What do you want the behavior to be when the number is greater than 3 digits, ie won't fit?
I'm pretty sure that the second pattern is ignored, and only the parts specific to the negation are used, e.g. the - sign or () etc.
That's my understanding of reading the following passage from the JavaDocs