public class DecimalFormatDemo
1: //DecimalFormatDemo.java
2: //Illustrates the DecimalFormat class.
3:
4: import java.text.DecimalFormat;
5:
6: public class DecimalFormatDemo
7: {
8: public static void main(String[] args)
9: {
10: DecimalFormat twoDigitsPastPoint = new DecimalFormat("0.00");
11: DecimalFormat threeDigitsPastPoint = new DecimalFormat("00.000");
12:
13: double d = 12.3456789;
14: System.out.println(twoDigitsPastPoint.format(d));
15: System.out.println(threeDigitsPastPoint.format(d));
16:
17: double money = 12.8;
18: System.out.println("$" + twoDigitsPastPoint.format(money));
19: String numberString = twoDigitsPastPoint.format(money);
20: System.out.println(numberString);
21:
22: DecimalFormat percent = new DecimalFormat("0.00%");
23:
24: double fraction = 0.734;
25: System.out.println(percent.format(fraction));
26:
27: //1 or 2 digits before decimal point:
28: DecimalFormat eNotation1 = new DecimalFormat("#0.###E0");
29: //2 digits before decimal point:
30: DecimalFormat eNotation2 = new DecimalFormat("00.###E0");
31:
32: double number = 123.456;
33: System.out.println(eNotation1.format(number));
34: System.out.println(eNotation2.format(number));
35:
36: double small = 0.0000123456;
37: System.out.println(eNotation1.format(small));
38: System.out.println(eNotation2.format(small));
39: }
40: }