Source of OutputFormat.java


  1: /** Solution to Self-Test Question 30. */
  2: public class OutputFormat
  3: {
  4:     /**
  5:      Displays a number with digitsAfterPoint digits after
  6:      the decimal point. Rounds any extra digits.
  7:      Does not advance to the next line after output.
  8:         */
  9:     public static void write(double number, int digitsAfterPoint)
 10:     {
 11:         if (number >= 0)
 12:             writePositive(number, digitsAfterPoint);
 13:         else
 14:         {
 15:             double positiveNumber = -number; 
 16:             System.out.print('-');
 17:             writePositive(positiveNumber, digitsAfterPoint);
 18:         }
 19:     }
 20:         
 21:     /**
 22:      Displays a number with digitsAfterPoint digits after
 23:      the decimal point. Rounds any extra digits.
 24:      Advances to the next line after output.
 25:     */
 26:         public static void writeln(double number, int digitsAfterPoint)
 27:     {
 28:        write(number, digitsAfterPoint);
 29:        System.out.println( );
 30:     }
 31:         
 32:     //Precondition: number >= 0
 33:     //Displays a number with digitsAfterPoint digits after 
 34:     //the decimal point. Rounds any extra digits.
 35:         private static void writePositive(double number, int digitsAfterPoint)
 36:     {
 37:         int mover = (int)(Math.pow(10, digitsAfterPoint));
 38:                       //1 followed by digitsAfterPoint zeros
 39:         int allWhole; //number with the decimal point
 40:                       //moved digitsAfterPoint places
 41:         allWhole = (int)(Math.round(number * mover)); 
 42:         int beforePoint = allWhole / mover;
 43:         int afterPoint = allWhole % mover; 
 44:         System.out.print(beforePoint);
 45:         System.out.print('.');
 46:         writeFraction(afterPoint, digitsAfterPoint); 
 47:     }
 48:         
 49:     //Displays the integer afterPoint with enough zeros
 50:     //in front to make it digitsAfterPoint digits long.
 51:         private static void writeFraction(int afterPoint, int digitsAfterPoint)
 52:     {
 53:         int n = 1; 
 54:         while (n < digitsAfterPoint)
 55:         {
 56:             if (afterPoint < Math.pow(10, n))
 57:                 System.out.print('0');
 58:             n = n + 1;
 59:         }
 60:         System.out.print(afterPoint);
 61:     }
 62:         
 63:         public static void main(String[] args)
 64:         {
 65:                 double number = 123.456789;
 66:         System.out.println("Testing with the number 123.456789:");
 67:                 writeln(number, 0);
 68:                 writeln(number, 1);
 69:                 writeln(number, 2);
 70:                 writeln(number, 3);
 71:                 writeln(number, 4);
 72:                 writeln(number, 5);
 73:                 writeln(number, 6);
 74:                 writeln(number, 7);
 75:         }
 76: }