Formatting Decimal Outputs
Formatting Decimal Output.
In the last webpage we developed two methods to compute the circumference
and area of a circle based on user input. You should have noticed
that using double precision results in the display of a lot of not
particularly useful digits. This webpage will present a bit
about the DecimalFormat classes in the
java.text package in order to improve
on such things. The program we will work on is just a slight modification of the CircleInfo.java program of the last webpage. The only changes to the code are highlighted in a purplish color. This first set of code should be called CircleInfoDF.java. |
import java.awt.Container; import javax.swing.*; import java.text.DecimalFormat; public class CircleInfoDF extends JApplet {
} |
Before we discuss the program you should develop the HTML file called CircleInfoDF.html. |
<html> <applet code="CircleInfoDF.class" width=300 height=150> </applet> </html> |
We rerun the program with the same input of a radius of 5.40 and we get the following |
Which differs quite appropriately from what we got without the DecimalFormat. |
Notice the only real changes to the code are
DecimalFormat threeDigits = new DecimalFormat("0.000");
threeDigits.format(area)
We could create any other formatting for the number of digits in the same way. |