public class Dollars
1:
2: public class Dollars
3: {
4: /**
5: Outputs amount in dollars and cents notation.
6: Rounds after two decimal points.
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: //Outputs amount in dollars and cents notation. Rounds
27: //after two decimal points. 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('.');
35: if (cents < 10)
36: {
37: System.out.print('0');
38: System.out.print(cents);
39: }
40: else
41: System.out.print(cents);
42: }
43:
44: /**
45: Outputs amount in dollars and cents notation.
46: Rounds after two decimal points.
47: Advances to the next line after output.
48: */
49: public static void writeln(double amount)
50: {
51: write(amount);
52: System.out.println( );
53: }
54: }