home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / javafile / ch02 / BigNum.java < prev    next >
Encoding:
Text File  |  1998-12-14  |  1.3 KB  |  49 lines

  1. /*
  2.  * BigNum.class converts a very large number to a string
  3.  * and then prints it out
  4.  */
  5. class BigNum {
  6.  
  7. public static void main (String args[]) {
  8.  
  9. /*
  10.  * Good thing longs are 64 bits! 
  11.  */
  12.     long debt = 3965170506502L; 
  13.     long pop = 250410000;
  14.  
  15.     print ("The 1992 national debt was $", debt);
  16.     print ("The  1992 population was ", pop);
  17.     print ("Each person owed $", debt/pop);
  18. }
  19.  
  20. /*
  21.  * print method converts a long to a string with commas
  22. * for easy reading.  We need it with these big numbers!
  23.  *    String str        preceding label
  24.  *     long n        the long to format and print
  25.  */
  26. public static void print (String str,long n) {
  27.     System.out.print (str);        // print the label
  28.     String buf = String.valueOf (n);    // Integer to String
  29.  
  30.     int start, end, ncommas, i;
  31.     int buflen = buf.length ();
  32.  
  33. /*
  34.  * It's a crazy algorithm, It works from left to right
  35. */
  36.     ncommas = buflen/3;
  37.     if (ncommas * 3 == buflen) ncommas -= 1; 
  38.     start = 0;
  39.     end = buflen-(3*ncommas);
  40.     System.out.print (buf.substring (start, end));
  41.     for (i=0; i<ncommas; i+=1) {
  42.         start = end;
  43.         end = start+3;
  44.         System.out.print (",");
  45.         System.out.print (buf.substring (start, end));
  46.     }
  47.     System.out.println ("");    // The final newline
  48. }
  49. }