KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Format


1 /*
2  * Cay S. Horstmann & Gary Cornell, Core Java
3  * Published By Sun Microsystems Press/Prentice-Hall
4  * Copyright (C) 1997 Sun Microsystems Inc.
5  * All Rights Reserved.
6  *
7  * Permission to use, copy, modify, and distribute this
8  * software and its documentation for NON-COMMERCIAL purposes
9  * and without fee is hereby granted provided that this
10  * copyright notice appears in all copies.
11  *
12  * THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR
13  * WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER
14  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
16  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS
17  * AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED
18  * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
19  * THIS SOFTWARE OR ITS DERIVATIVES.
20  */

21  
22 /**
23  * A class for formatting numbers that follows printf conventions.
24  * Also implements C-like atoi and atof functions
25  * @version 1.04 13 Sep 1998
26  * @author Cay Horstmann
27  */

28
29 import java.io.*;
30
31 public class Format
32
33 { /**
34   * Formats the number following printf conventions.
35   * Main limitation: Can only handle one format parameter at a time
36   * Use multiple Format objects to format more than one number
37   * @param s the format string following printf conventions
38   * The string has a prefix, a format code and a suffix. The prefix and suffix
39   * become part of the formatted output. The format code directs the
40   * formatting of the (single) parameter to be formatted. The code has the
41   * following structure
42   * <ul>
43   * <li> a % (required)
44   * <li> a modifier (optional)
45   * <dl>
46   * <dt> + <dd> forces display of + for positive numbers
47   * <dt> 0 <dd> show leading zeroes
48   * <dt> - <dd> align left in the field
49   * <dt> space <dd> prepend a space in front of positive numbers
50   * <dt> # <dd> use "alternate" format. Add 0 or 0x for octal or hexadecimal numbers. Don't suppress trailing zeroes in general floating point format.
51   * </dl>
52   * <li> an integer denoting field width (optional)
53   * <li> a period followed by an integer denoting precision (optional)
54   * <li> a format descriptor (required)
55   * <dl>
56   * <dt>f <dd> floating point number in fixed format
57   * <dt>e, E <dd> floating point number in exponential notation (scientific format). The E format results in an uppercase E for the exponent (1.14130E+003), the e format in a lowercase e.
58   * <dt>g, G <dd> floating point number in general format (fixed format for small numbers, exponential format for large numbers). Trailing zeroes are suppressed. The G format results in an uppercase E for the exponent (if any), the g format in a lowercase e.
59   * <dt>d, i <dd> integer in decimal
60   * <dt>x <dd> integer in hexadecimal
61   * <dt>o <dd> integer in octal
62   * <dt>s <dd> string
63   * <dt>c <dd> character
64   * </dl>
65   * </ul>
66   * @exception IllegalArgumentException if bad format
67   */

68
69    public Format(String JavaDoc s)
70    { width = 0;
71       precision = -1;
72       pre = "";
73       post = "";
74       leading_zeroes = false;
75       show_plus = false;
76       alternate = false;
77       show_space = false;
78       left_align = false;
79       fmt = ' ';
80       
81       int state = 0;
82       int length = s.length();
83       int parse_state = 0;
84       // 0 = prefix, 1 = flags, 2 = width, 3 = precision,
85
// 4 = format, 5 = end
86
int i = 0;
87       
88       while (parse_state == 0)
89       { if (i >= length) parse_state = 5;
90          else if (s.charAt(i) == '%')
91          { if (i < length - 1)
92             { if (s.charAt(i + 1) == '%')
93                { pre = pre + '%';
94                   i++;
95                }
96                else
97                   parse_state = 1;
98             }
99             else throw new java.lang.IllegalArgumentException JavaDoc();
100          }
101          else
102             pre = pre + s.charAt(i);
103          i++;
104       }
105       while (parse_state == 1)
106       { if (i >= length) parse_state = 5;
107          else if (s.charAt(i) == ' ') show_space = true;
108          else if (s.charAt(i) == '-') left_align = true;
109          else if (s.charAt(i) == '+') show_plus = true;
110          else if (s.charAt(i) == '0') leading_zeroes = true;
111          else if (s.charAt(i) == '#') alternate = true;
112          else { parse_state = 2; i--; }
113          i++;
114       }
115       while (parse_state == 2)
116       { if (i >= length) parse_state = 5;
117          else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
118          { width = width * 10 + s.charAt(i) - '0';
119             i++;
120          }
121          else if (s.charAt(i) == '.')
122          { parse_state = 3;
123             precision = 0;
124             i++;
125          }
126          else
127             parse_state = 4;
128       }
129       while (parse_state == 3)
130       { if (i >= length) parse_state = 5;
131          else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
132          { precision = precision * 10 + s.charAt(i) - '0';
133             i++;
134          }
135          else
136             parse_state = 4;
137       }
138       if (parse_state == 4)
139       { if (i >= length) parse_state = 5;
140          else fmt = s.charAt(i);
141          i++;
142       }
143       if (i < length)
144          post = s.substring(i, length);
145    }
146
147   /**
148   * prints a formatted number following printf conventions
149   * @param s a PrintStream
150   * @param fmt the format string
151   * @param x the double to print
152   */

153   
154    public static void print(java.io.PrintStream JavaDoc s, String JavaDoc fmt, double x)
155    { s.print(new Format(fmt).form(x));
156    }
157
158   /**
159   * prints a formatted number following printf conventions
160   * @param s a PrintStream
161   * @param fmt the format string
162   * @param x the long to print
163   */

164   public static void print(java.io.PrintStream JavaDoc s, String JavaDoc fmt, long x)
165    { s.print(new Format(fmt).form(x));
166    }
167
168   /**
169   * prints a formatted number following printf conventions
170   * @param s a PrintStream
171   * @param fmt the format string
172   * @param x the character to
173   */

174   
175    public static void print(java.io.PrintStream JavaDoc s, String JavaDoc fmt, char x)
176    { s.print(new Format(fmt).form(x));
177    }
178
179   /**
180   * prints a formatted number following printf conventions
181   * @param s a PrintStream, fmt the format string
182   * @param x a string that represents the digits to print
183   */

184   
185    public static void print(java.io.PrintStream JavaDoc s, String JavaDoc fmt, String JavaDoc x)
186    { s.print(new Format(fmt).form(x));
187    }
188    
189   /**
190   * Converts a string of digits (decimal, octal or hex) to an integer
191   * @param s a string
192   * @return the numeric value of the prefix of s representing a base 10 integer
193   */

194   
195    public static int atoi(String JavaDoc s)
196    { return (int)atol(s);
197    }
198    
199   /**
200   * Converts a string of digits (decimal, octal or hex) to a long integer
201   * @param s a string
202   * @return the numeric value of the prefix of s representing a base 10 integer
203   */

204   
205    public static long atol(String JavaDoc s)
206    { int i = 0;
207
208       while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
209       if (i < s.length() && s.charAt(i) == '0')
210       { if (i + 1 < s.length() && (s.charAt(i + 1) == 'x' || s.charAt(i + 1) == 'X'))
211             return parseLong(s.substring(i + 2), 16);
212          else return parseLong(s, 8);
213       }
214       else return parseLong(s, 10);
215    }
216
217    private static long parseLong(String JavaDoc s, int base)
218    { int i = 0;
219       int sign = 1;
220       long r = 0;
221       
222       while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
223       if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
224       else if (i < s.length() && s.charAt(i) == '+') { i++; }
225       while (i < s.length())
226       { char ch = s.charAt(i);
227          if ('0' <= ch && ch < '0' + base)
228             r = r * base + ch - '0';
229          else if ('A' <= ch && ch < 'A' + base - 10)
230             r = r * base + ch - 'A' + 10 ;
231          else if ('a' <= ch && ch < 'a' + base - 10)
232             r = r * base + ch - 'a' + 10 ;
233          else
234             return r * sign;
235          i++;
236       }
237       return r * sign;
238    }
239       
240    /**
241    * Converts a string of digits to an double
242    * @param s a string
243    */

244    
245    public static double atof(String JavaDoc s)
246    { int i = 0;
247       int sign = 1;
248       double r = 0; // integer part
249
double f = 0; // fractional part
250
double p = 1; // exponent of fractional part
251
int state = 0; // 0 = int part, 1 = frac part
252

253       while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
254       if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
255       else if (i < s.length() && s.charAt(i) == '+') { i++; }
256       while (i < s.length())
257       { char ch = s.charAt(i);
258          if ('0' <= ch && ch <= '9')
259          { if (state == 0)
260                r = r * 10 + ch - '0';
261             else if (state == 1)
262             { p = p / 10;
263                r = r + p * (ch - '0');
264             }
265          }
266          else if (ch == '.')
267          { if (state == 0) state = 1;
268             else return sign * r;
269          }
270          else if (ch == 'e' || ch == 'E')
271          { long e = (int)parseLong(s.substring(i + 1), 10);
272             return sign * r * Math.pow(10, e);
273          }
274          else return sign * r;
275          i++;
276       }
277       return sign * r;
278    }
279             
280    /**
281    * Formats a double into a string (like sprintf in C)
282    * @param x the number to format
283    * @return the formatted string
284    * @exception IllegalArgumentException if bad argument
285    */

286    
287    public String JavaDoc form(double x)
288    { String JavaDoc r;
289       if (precision < 0) precision = 6;
290       int s = 1;
291       if (x < 0) { x = -x; s = -1; }
292       if (fmt == 'f')
293          r = fixed_format(x);
294       else if (fmt == 'e' || fmt == 'E' || fmt == 'g' || fmt == 'G')
295          r = exp_format(x);
296       else throw new java.lang.IllegalArgumentException JavaDoc();
297       
298       return pad(sign(s, r));
299    }
300    
301    /**
302    * Formats a long integer into a string (like sprintf in C)
303    * @param x the number to format
304    * @return the formatted string
305    */

306    
307    public String JavaDoc form(long x)
308    { String JavaDoc r;
309       int s = 0;
310       if (fmt == 'd' || fmt == 'i')
311       { if (x < 0)
312          { r = ("" + x).substring(1);
313             s = -1;
314          }
315          else
316          { r = "" + x;
317             s = 1;
318          }
319       }
320       else if (fmt == 'o')
321          r = convert(x, 3, 7, "01234567");
322       else if (fmt == 'x')
323          r = convert(x, 4, 15, "0123456789abcdef");
324       else if (fmt == 'X')
325          r = convert(x, 4, 15, "0123456789ABCDEF");
326       else throw new java.lang.IllegalArgumentException JavaDoc();
327          
328       return pad(sign(s, r));
329    }
330    
331    /**
332    * Formats a character into a string (like sprintf in C)
333    * @param x the value to format
334    * @return the formatted string
335    */

336    
337    public String JavaDoc form(char c)
338    { if (fmt != 'c')
339          throw new java.lang.IllegalArgumentException JavaDoc();
340
341       String JavaDoc r = "" + c;
342       return pad(r);
343    }
344    
345    /**
346    * Formats a string into a larger string (like sprintf in C)
347    * @param x the value to format
348    * @return the formatted string
349    */

350    
351    public String JavaDoc form(String JavaDoc s)
352    { if (fmt != 's')
353          throw new java.lang.IllegalArgumentException JavaDoc();
354       if (precision >= 0 && precision < s.length())
355           s = s.substring(0, precision);
356       return pad(s);
357    }
358    
359     
360    /**
361    * a test stub for the format class
362    */

363    
364    public static void main(String JavaDoc[] a)
365    { double x = 1.23456789012;
366       double y = 123;
367       double z = 1.2345e30;
368       double w = 1.02;
369       double u = 1.234e-5;
370       int d = 0xCAFE;
371       Format.print(System.out, "x = |%f|\n", x);
372       Format.print(System.out, "u = |%20f|\n", u);
373       Format.print(System.out, "x = |% .5f|\n", x);
374       Format.print(System.out, "w = |%20.5f|\n", w);
375       Format.print(System.out, "x = |%020.5f|\n", x);
376       Format.print(System.out, "x = |%+20.5f|\n", x);
377       Format.print(System.out, "x = |%+020.5f|\n", x);
378       Format.print(System.out, "x = |% 020.5f|\n", x);
379       Format.print(System.out, "y = |%#+20.5f|\n", y);
380       Format.print(System.out, "y = |%-+20.5f|\n", y);
381       Format.print(System.out, "z = |%20.5f|\n", z);
382       
383       Format.print(System.out, "x = |%e|\n", x);
384       Format.print(System.out, "u = |%20e|\n", u);
385       Format.print(System.out, "x = |% .5e|\n", x);
386       Format.print(System.out, "w = |%20.5e|\n", w);
387       Format.print(System.out, "x = |%020.5e|\n", x);
388       Format.print(System.out, "x = |%+20.5e|\n", x);
389       Format.print(System.out, "x = |%+020.5e|\n", x);
390       Format.print(System.out, "x = |% 020.5e|\n", x);
391       Format.print(System.out, "y = |%#+20.5e|\n", y);
392       Format.print(System.out, "y = |%-+20.5e|\n", y);
393       
394       Format.print(System.out, "x = |%g|\n", x);
395       Format.print(System.out, "z = |%g|\n", z);
396       Format.print(System.out, "w = |%g|\n", w);
397       Format.print(System.out, "u = |%g|\n", u);
398       Format.print(System.out, "y = |%.2g|\n", y);
399       Format.print(System.out, "y = |%#.2g|\n", y);
400
401       Format.print(System.out, "d = |%d|\n", d);
402       Format.print(System.out, "d = |%20d|\n", d);
403       Format.print(System.out, "d = |%020d|\n", d);
404       Format.print(System.out, "d = |%+20d|\n", d);
405       Format.print(System.out, "d = |% 020d|\n", d);
406       Format.print(System.out, "d = |%-20d|\n", d);
407       Format.print(System.out, "d = |%20.8d|\n", d);
408       Format.print(System.out, "d = |%x|\n", d);
409       Format.print(System.out, "d = |%20X|\n", d);
410       Format.print(System.out, "d = |%#20x|\n", d);
411       Format.print(System.out, "d = |%020X|\n", d);
412       Format.print(System.out, "d = |%20.8x|\n", d);
413       Format.print(System.out, "d = |%o|\n", d);
414       Format.print(System.out, "d = |%020o|\n", d);
415       Format.print(System.out, "d = |%#20o|\n", d);
416       Format.print(System.out, "d = |%#020o|\n", d);
417       Format.print(System.out, "d = |%20.12o|\n", d);
418       
419       Format.print(System.out, "s = |%-20s|\n", "Hello");
420       Format.print(System.out, "s = |%-20c|\n", '!');
421
422       // regression test to confirm fix of reported bugs
423

424       Format.print(System.out, "|%i|\n", Long.MIN_VALUE);
425
426       Format.print(System.out, "|%6.2e|\n", 0.0);
427       Format.print(System.out, "|%6.2g|\n", 0.0);
428
429       Format.print(System.out, "|%6.2f|\n", 9.99);
430       Format.print(System.out, "|%6.2f|\n", 9.999);
431
432       Format.print(System.out, "|%6.0f|\n", 9.999);
433    }
434    
435    private static String JavaDoc repeat(char c, int n)
436    { if (n <= 0) return "";
437       StringBuffer JavaDoc s = new StringBuffer JavaDoc(n);
438       for (int i = 0; i < n; i++) s.append(c);
439       return s.toString();
440    }
441
442    private static String JavaDoc convert(long x, int n, int m, String JavaDoc d)
443    { if (x == 0) return "0";
444       String JavaDoc r = "";
445       while (x != 0)
446       { r = d.charAt((int)(x & m)) + r;
447          x = x >>> n;
448       }
449       return r;
450    }
451
452    private String JavaDoc pad(String JavaDoc r)
453    { String JavaDoc p = repeat(' ', width - r.length());
454       if (left_align) return pre + r + p + post;
455       else return pre + p + r + post;
456    }
457    
458    private String JavaDoc sign(int s, String JavaDoc r)
459    { String JavaDoc p = "";
460       if (s < 0) p = "-";
461       else if (s > 0)
462       { if (show_plus) p = "+";
463          else if (show_space) p = " ";
464       }
465       else
466       { if (fmt == 'o' && alternate && r.length() > 0 && r.charAt(0) != '0') p = "0";
467          else if (fmt == 'x' && alternate) p = "0x";
468          else if (fmt == 'X' && alternate) p = "0X";
469       }
470       int w = 0;
471       if (leading_zeroes)
472          w = width;
473       else if ((fmt == 'd' || fmt == 'i' || fmt == 'x' || fmt == 'X' || fmt == 'o')
474          && precision > 0) w = precision;
475       
476       return p + repeat('0', w - p.length() - r.length()) + r;
477    }
478    
479    private String JavaDoc fixed_format(double d)
480    { boolean removeTrailing
481          = (fmt == 'G' || fmt == 'g') && !alternate;
482          // remove trailing zeroes and decimal point
483

484       if (d > 0x7FFFFFFFFFFFFFFFL) return exp_format(d);
485       if (precision == 0)
486          return (long)(d + 0.5) + (removeTrailing ? "" : ".");
487
488       long whole = (long)d;
489       double fr = d - whole; // fractional part
490
if (fr >= 1 || fr < 0) return exp_format(d);
491
492       double factor = 1;
493       String JavaDoc leading_zeroes = "";
494       for (int i = 1; i <= precision && factor <= 0x7FFFFFFFFFFFFFFFL; i++)
495       { factor *= 10;
496          leading_zeroes = leading_zeroes + "0";
497       }
498       long l = (long) (factor * fr + 0.5);
499       if (l >= factor) { l = 0; whole++; } // CSH 10-25-97
500

501       String JavaDoc z = leading_zeroes + l;
502       z = "." + z.substring(z.length() - precision, z.length());
503
504       if (removeTrailing)
505       { int t = z.length() - 1;
506          while (t >= 0 && z.charAt(t) == '0') t--;
507          if (t >= 0 && z.charAt(t) == '.') t--;
508          z = z.substring(0, t + 1);
509       }
510
511       return whole + z;
512    }
513
514    private String JavaDoc exp_format(double d)
515    { String JavaDoc f = "";
516       int e = 0;
517       double dd = d;
518       double factor = 1;
519       if (d != 0)
520       { while (dd > 10) { e++; factor /= 10; dd = dd / 10; }
521          while (dd < 1) { e--; factor *= 10; dd = dd * 10; }
522       }
523       if ((fmt == 'g' || fmt == 'G') && e >= -4 && e < precision)
524          return fixed_format(d);
525       
526       d = d * factor;
527       f = f + fixed_format(d);
528       
529       if (fmt == 'e' || fmt == 'g')
530          f = f + "e";
531       else
532          f = f + "E";
533
534       String JavaDoc p = "000";
535       if (e >= 0)
536       { f = f + "+";
537          p = p + e;
538       }
539       else
540       { f = f + "-";
541          p = p + (-e);
542       }
543          
544       return f + p.substring(p.length() - 3, p.length());
545    }
546    
547    private int width;
548    private int precision;
549    private String JavaDoc pre;
550    private String JavaDoc post;
551    private boolean leading_zeroes;
552    private boolean show_plus;
553    private boolean alternate;
554    private boolean show_space;
555    private boolean left_align;
556    private char fmt; // one of cdeEfgGiosxXos
557
}
558
559
560
561
562
563
Popular Tags