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
System.out.println(String.format("%06.2f%n",1.3));
System.out.println(String.format("%06.2f%n",-3.323));
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
A DecimalFormat pattern contains a positive and negative subpattern, for example, "#,##0.00;(#,##0.00)". Each subpattern has a prefix, numeric part, and suffix. The negative subpattern is optional; if absent, then the positive subpattern prefixed with the localized minus sign ('-' in most locales) is used as the negative subpattern. That is, "0.00" alone is equivalent to "0.00;-0.00". If there is an explicit negative subpattern, it serves only to specify the negative prefix and suffix; the number of digits, minimal digits, and other characteristics are all the same as the positive pattern. That means that "#,##0.0#;(#)" produces precisely the same behavior as "#,##0.0#;(#,##0.0#)".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With