Optional Format for Negative Numbers

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
Historical topic: Java appletsModern web browsers do not run Java applets. The Applet API was deprecated for removal before Java 25 and was removed in Java 26. Treat applet examples on this page as historical object-oriented/GUI examples; for new desktop interfaces use Swing where appropriate or JavaFX/OpenJFX.
go to previous page   go to home page   go to next page        
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

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.

Embedded Java applet removed: modern browsers do not support Java applets. The surrounding source code is retained for historical study.

Try some patterns like 0.0;-0.0.

QUESTION 13:

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) ); 

Copy and paste from the fragment into the applet to see the answers. But first work out the answer on your own.