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