Java: formatting decimal numbers, part 0

We’re getting into a serious topic. The tutor rolls up his sleeves.

In math, formatting rarely matters.  If the correct answer is 0.012, you can answer as 1.2e-2, 3/250, or 0.01200. Most computer environments, like most calculators, give an “unformatted” answer to a calculation. Not too surprisingly, when I ask Java for the square root of 14, it gives 3.7416573867739413, which is perhaps more than sufficient.

In physics, chemistry, or financial contexts, people aren’t as tolerant of unformatted answers. Scientists expect answers to correct precision. Monetary values are expected to two decimal places.

Java has a class that helps the programmer to display numeric output according to any desired format: DecimalFormat. It’s invoked with a pattern that describes the desired format. An example:

DecimalFormat form0 = new DecimalFormat(“#,###.00”);

In order to use the DecimalFormat class, you must include the line

import java.text.DecimalFormat;

above the class declaration.

Following is a short program that illustrates the use of Java’s DecimalFormat. (It uses the Java Scanner, about which I wrote a series starting here.)


import java.text.DecimalFormat;
import java.util.Scanner;//needed for the scanner

class DecFormatEx{
/*This class reads numbers given with the command call, then displays them formatted to two decimal places with the thousands separated by commas.*/
public static void main(String[] args){

DecimalFormat dec0=new DecimalFormat(“#,###.00”);
double num0;
String string0;
for(int i=0;i Scanner scan0=new Scanner(args[i]);
if(scan0.hasNextDouble()){
num0=scan0.nextDouble();
string0=dec0.format(num0);
System.out.println(“The number, formatted, is “+string0+”\n”);
}
else{
System.out.println(args[i] + ” not a readable number.\n”);
}
}//end of for loop
System.out.println(“\nSee you again:)\n\n”);
}//end of main
}//end of class

Let’s imagine you save the above program as DecFormatEx.java, then compile it as follows:

javac DecFormatEx.java

Finally, you run it with the following command call:

java DecFormatEx 1139.726 23 0.113e1 2000000.29

You’ll hopefully receive the output

The number, formatted, is 1,139.73
The number, formatted, is 23.00
The number, formatted, is 1.13
The number, formatted, is 2,000,000.29

As usual, this little Java program needs more explanation than fits in one post. I’ll be continuing about it tomorrow.

HTH:)

Source:

docs.oracle.com

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Tagged with: , , , , , ,

Leave a Reply