DecimalFormat numform = new DecimalFormat("-0.00"); System.out.println( "Num = " + numform.format(-924.56) );
Num = --924.56
Minus signs in the format pattern can be a problem.
The format pattern has an optional second half which shows how to treat negative numbers. The pattern looks like
positivePattern;negativePattern
A semicolon separates the two subpatterns.
To avoid problems, make the pattern for the digits in positivePattern
the same as in negativePattern
.
(This is not a formal rule, just good advice.)
However, both patterns can contain additional characters
on either side of the patterns for the digits.
Put a space in the positivePattern
where a negative sign appears in the negativePattern
.
For example
DecimalFormat numform = new DecimalFormat(" 00.00;-00.00"); System.out.println( "Pos = " + numform.format(12.6) ); System.out.println( "Neg = " + numform.format(-12.6) );
The positivePattern
in this example starts with a space.
The negativePattern
starts with a minus sign.
The program fragment outputs:
Pos = 12.60 Neg = -12.60
This is useful for writing out positive and negative numbers in columns with the decimal separators aligned. Here is the applet.
Try some patterns like 0.0;-0.0
.
What does the following fragment write?
Copy and paste from the fragment into the applet to see the answers. But first work out the answer on your own.