Java API: [Link].
DecimalFormat
• The DecimalFormat class provides a way to control the appearance of numbers
that are stored as String’s.
• You create an instance of DecimalFormat for each format you want to use.
• Note: Have to import the DecimalFormat class from the [Link] package:
import [Link];
1
• Example:
• Want to print integers with the commas, as in: 27,387,982 or 37,298.
int oneNum = 27387982;
int nextNum = 37298;
DecimalFormat commaFormat;
commaFormat = new DecimalFormat("#,###");
[Link]("oneNum = " + [Link](oneNum));
[Link]("nextNum = " + [Link](nextNum));
• The # symbol means to print a digit, but to not print leading zeroes.
• The , in the format indicates where to put the commas in the final number.
2
• The DecimalFormat class can specify floating-point (float and double)
values as well as integer values.
• The format string: #,###.## indicates the answer is to have no more than two
decimal places.
• The value will be correctly rounded automatically when printed.
• Example: The output:
import [Link]; oneNumber = 3.14
nextNumber = 3,827,967.3
public class FormatExample2 {
public static void main(String[] args) {
float oneNum = 3.14159F;
double nextNum = 3827967.29836598263987649826395809384756;
DecimalFormat commaFormat; Why only one
commaFormat = new DecimalFormat("#,###.##"); decimal place?
String myPi = [Link](oneNum);
[Link]("oneNum = " + [Link](oneNum));
[Link]("nextNum = " + [Link](nextNum));
}
}
3
• If you need two (or more) different formats in a program, you can declare multiple
instances of DecimalFormat.
import [Link];
public class Pennies {
public static void main(String[] args) {
float myBalance = 3426.07F;
float myInterest;
DecimalFormat dollarFormat = new DecimalFormat("$ #,##0.00");
DecimalFormat pennyFormat = new DecimalFormat("#,###");
myInterest = myBalance * 3.5F / 100; // 3.5% interest rate
[Link]("Interest earned = ");
[Link]([Link](myInterest));
[Link]("Pennies earned = ");
[Link]([Link](myInterest * 100));
}
}
4