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