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) );
A = 24.80 B = -92.78 C = 00.01 D = -00.12
In financial output, negative numbers are sometimes enclosed in
() without a minus sign.
Here is a fragment that does that:
double firstQ= 456.78, secondQ= -23.06, thirdQ= 46.3, fourthQ= -102.45;
DecimalFormat numform = new DecimalFormat(" 000.00 ;(000.00)");
System.out.println( "First Quarter = " + numform.format(firstQ) );
System.out.println( "Second Quarter = " + numform.format(secondQ) );
System.out.println( "Third Quarter = " + numform.format(thirdQ) );
System.out.println( "Fourth Quarter = " + numform.format(fourthQ) );
The fragment outputs:
First Quarter = 456.78 Second Quarter = (023.06) Third Quarter = 046.30 Fourth Quarter = (102.45)
Notice that the number format pattern is the same in both subpatterns,
000.00.
The pattern for positive numbers includes two spaces to match the
two parentheses output for negative numbers.
What does the following fragment write?
double A= 0.1, B= -0.1;
DecimalFormat numform = new DecimalFormat(" 000.000;-000.000");
System.out.println( "A = " + numform.format(A) );
System.out.println( "B = " + numform.format(B) );