Using just one Pattern

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.
go to previous page   go to home page   go to next page        
double A= 123.1, B= -1.1;
DecimalFormat numform = new DecimalFormat(" ##0.###;-##0.###");
System.out.println( "A = " + numform.format(A) );
System.out.println( "B = " + numform.format(B) );

Answer:

A =  123.1
B = -1.1

Using just one Pattern

If you are using #, there is usually little benefit in also using a subpattern for negative numbers. Find a pattern that works well for the range of numbers you expect to write.

The format pattern ###0.0### works well for typical floating point numbers. Add more #s on the left for larger numbers or on the right for greater accuracy. The pattern ###0 works well for typical integers.

QUESTION 17:

(Trick Question: ) What does the following fragment write:

int A= 12, B= -456;

DecimalFormat numform = new DecimalFormat("###0.0###"); 

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

Hint: what types are the variables?