Decimal places

In Lab 4 you will be displaying double values. These can have rather long decimal values. Java provides a way to format these numbers so that they are more managable for printing. Here is an example:

// you must use this import line at the top of the ComputeFigure file (with the other import statements)

import java.text.*;

// For setting 2 decimal places for the format.
//you can put this at the beginning of the paint() method.

NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);

//use this (replace area with whatever variable you are using)
//to print out the formatted information.

g.drawString("Area= " + nf.format(area), 120,120);

See http://java.sun.com/j2se/1.5/docs/api/java/text/NumberFormat.html for SDK v1.5

Lewis and Loftus text, Chapter 3 also has information on these classes for formatting (and Math).


Another technique:

DecimalFormat myFormat1 = new DecimalFormat("###,###.##");
DecimalFormat myFormat2 = new DecimalFormat("####,###");

...

g.drawString("  Circle area:" + myFormat1.format(myCircleArea),10,50);
g.drawString("  Rectangle area:" + myFormat2.format(myRectArea),10,50);
See http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html