The decimal margin of the subpattern does not work correctly

I use DecimalFormat to create a formatted decimal that always contains 6 characters. At first I used the format string new DecimalFormat("000.00") , but this gave me an error for negative numbers. A minus sign is added and makes space number one large, resulting in -005.25 , rather than -05.25 as desired.

I was 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 a character ; to format negative numbers differently than positive numbers. I could not do this job correctly. As far as I understand, the following code should work the same as above.

 DecimalFormat fmt = new DecimalFormat("000.00;00.00"); System.out.println(fmt.format(netAmt)); 

The result is that the pattern is before ; It is used for both negative and positive numbers that cause the error -005.25 . What am I doing wrong? I do not understand why ; ?

+5
java decimalformat
source share
2 answers

Does the following line pattern help you: "%06.2f%n" Fixed width 6 s "0" filling 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 more than 3 digits, i.e. not fit?

+4
source share

I am sure that the second pattern is ignored and only the parts specific to the negation are used. sign or (), etc.

This is my understanding of reading the following excerpt from JavaDocs

The DecimalFormat pattern contains a positive and negative subpattern, for example, "#, ## 0.00; (#, ## 0.00)". Each subpattern has a prefix, a numeric part, and a suffix. A negative subpattern is optional; if absent, then the negative subpattern with the localized minus prefix ('-' in most locales) is used as a negative subpattern. That is, "0.00" one is equivalent to "0.00; -0.00". If there is an explicit negative subpattern, it only serves to indicate a negative prefix and suffix; the number of digits, minimum digits and other characteristics is just like a positive pattern . This means that "#, ## 0.0 #; (#)" produces exactly the same behavior as "#, ## 0.0 #; (#, ## 0.0 #)".

+3
source share

All Articles