'0' Format Code

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

Answer:

Num = 13.46

The complete 13 was produced, even though there was only one zero left of the decimal point. Two digits were output to the right of the decimal point, as requested. The last digit was rounded.

'0' Format Code

The format pattern 000.00 asks that a number be converted into 6 characters, three digits on the left of the decimal separator, a decimal separator, and two digits on the right. However, all the digits that make up the integer part of the number are output, regardless of the format pattern.

This table shows how some doubles are converted to strings (using the US locale) under the direction of various format patterns. The doubles are 64-bit patterns contained in some variable, but the table shows them written out as decimals.

value of double format pattern output string
123.456
"000.000"
"123.456"
123.456
"000.0"  
"123.5"
123.456
"000"    
"123"
89.008
"000.000"  
"089.008"
89.008
"0.00"     
"89.01"
89.008
"0."       
"89."

The quote marks are not part of the output string. They are there to show the limits of the string. (Examples in pages to come show output strings that include spaces.) This applet demonstrates this. Enter a number and a format pattern, then click the button. Don't use quotation marks in the format pattern.

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

A bad number or a bad format pattern will cause an error message to be displayed. But DecimalFormat is quite forgiving about errors in the format pattern and will accept many patterns, even slightly flawed ones. Experiment with spaces and negative numbers.

Characters in the format pattern other than 0 and , are output unchanged, but may appear in unexpected places.

QUESTION 10:

What does the following fragment write?

DecimalFormat numform = new DecimalFormat("000,000.00"); 
System.out.println( "Num = " + numform.format(98765.432) );

Copy and Paste from the question into the applet to answer this question. Don't include the quote marks in the format pattern.