public class DollarFormat
1: //DollarFormat.java
2:
3: public class DollarFormat
4: {
5: /**
6: * Displays amount in dollars and cents notation.
7: * Rounds after two decimal places.
8: * Does not advance to the next line after output.
9: */
10: public static void write
11: (
12: double amount
13: )
14: {
15: if (amount >= 0)
16: {
17: System.out.print('$');
18: writePositive(amount);
19: }
20: else
21: {
22: double positiveAmount = -amount;
23: System.out.print('-');
24: System.out.print('$');
25: writePositive(positiveAmount);
26: }
27: }
28:
29: //Precondition: amount >= 0;
30: //Displays amount in dollars and cents notation.
31: //Rounds after two decimal places. Omits the dollar sign.
32: private static void writePositive
33: (
34: double amount
35: )
36: {
37: int allCents = (int)(Math.round(amount * 100));
38: int dollars = allCents / 100;
39: int cents = allCents % 100;
40: System.out.print(dollars);
41: System.out.print('.');
42:
43: if (cents < 10)
44: System.out.print('0');
45: System.out.print(cents);
46: }
47:
48: /**
49: * Displays amount in dollars and cents notation.
50: * Rounds after two decimal points.
51: * Advances to the next line after output.
52: */
53: public static void writeln
54: (
55: double amount
56: )
57: {
58: write(amount);
59: System.out.println();
60: }
61: }