go to previous page   go to home page   go to next page highlighting
DecimalFormat numform = new DecimalFormat("-0.00"); 
System.out.println( "Num = " + numform.format(-924.56) );

Answer:

Num = --924.56

Minus signs in the format pattern can be a problem.


Optional Format for Negative Numbers

A format pattern may have an optional second half which shows how to format negative numbers:

positivePattern;negativePattern

A semicolon separates the two subpatterns. If a number is positive (or zero) the first pattern is used. If a number is negative the second pattern is used.

A minus sign is not included in the output of a negative number if the negativePattern contains characters not in the positivePattern. It is assumed that the extra characters in the negativePattern are how you want to display negative values.

To avoid problems, the parts of both subpatterns that show how to format digits should be the same. The digits are always formatted according to the positivePattern. The negativePattern is used only for the extra characters it might contain.

For example, if the digit-formatting part of the sub-pattern for positive numbers is "000.00" then the digit-formatting part for negative numbers should be the same. However, both sub-patterns can contain additional characters. For example, you could start the subpattern for positive numbers with a space, and start the subpattern for negative numbers with a minus sign:

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 are some patterns to try:

"0.0;-0.0"   
"0.00;(0.00)"
"0.00; 0.00"

Notice that the last format string includes a space before the negative half. The space counts as an extra character and will suppress output of a negative sign. This could be a nasty bug!


QUESTION 11:

What does the following fragment write?

double A= 24.8, B= -92.777, C= 0.009, D= -0.123;

DecimalFormat numform = new DecimalFormat(" 00.00;-00.00"); 

System.out.println( "A = " + numform.format(A) ); 
System.out.println( "B = " + numform.format(B) ); 
System.out.println( "C = " + numform.format(C) ); 
System.out.println( "D = " + numform.format(D) ); 

go to previous page   go to home page   go to next page