2 * Gary Cornell and Cay S. Horstmann, Core Java (Book/CD-ROM)
3 * Published By SunSoft Press/Prentice-Hall
4 * Copyright (C) 1996 Sun Microsystems Inc.
5 * All Rights Reserved. ISBN 0-13-565755-5
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.
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.
23 * A class for formatting numbers that follows printf conventions.
24 * Also implements C-like atoi and atof functions
25 * @version 1.01 15 Feb 1996
26 * @author Cay Horstmann
36 * Formats the number following printf conventions.
37 * Main limitation: Can only handle one format parameter at a time
38 * Use multiple Format objects to format more than one number
39 * @param s the format string following printf conventions
40 * The string has a prefix, a format code and a suffix. The prefix and suffix
41 * become part of the formatted output. The format code directs the
42 * formatting of the (single) parameter to be formatted. The code has the
46 * <li> a modifier (optional)
48 * <dt> + <dd> forces display of + for positive numbers
49 * <dt> 0 <dd> show leading zeroes
50 * <dt> - <dd> align left in the field
51 * <dt> space <dd> prepend a space in front of positive numbers
52 * <dt> # <dd> use "alternate" format. Add 0 or 0x for octal or hexadecimal numbers. Don't suppress trailing zeroes in general floating point format.
54 * <li> an integer denoting field width (optional)
55 * <li> a period followed by an integer denoting precision (optional)
56 * <li> a format descriptor (required)
58 * <dt>f <dd> floating point number in fixed format
59 * <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.
60 * <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.
61 * <dt>d, i <dd> integer in decimal
62 * <dt>x <dd> integer in hexadecimal
63 * <dt>o <dd> integer in octal
65 * <dt>c <dd> character
68 * @exception IllegalArgumentException if bad format
71 public Format(String s)
76 leading_zeroes = false;
84 int length = s.length();
86 // 0 = prefix, 1 = flags, 2 = width, 3 = precision,
87 // 4 = format, 5 = end
90 while (parse_state == 0)
91 { if (i >= length) parse_state = 5;
92 else if (s.charAt(i) == '%')
94 { if (s.charAt(i + 1) == '%')
101 else throw new java.lang.IllegalArgumentException();
104 pre = pre + s.charAt(i);
107 while (parse_state == 1)
108 { if (i >= length) parse_state = 5;
109 else if (s.charAt(i) == ' ') show_space = true;
110 else if (s.charAt(i) == '-') left_align = true;
111 else if (s.charAt(i) == '+') show_plus = true;
112 else if (s.charAt(i) == '0') leading_zeroes = true;
113 else if (s.charAt(i) == '#') alternate = true;
116 else { parse_state = 2; i--; }
119 while (parse_state == 2)
120 { if (i >= length) parse_state = 5;
121 else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
122 { width = width * 10 + s.charAt(i) - '0';
125 else if (s.charAt(i) == '.')
133 while (parse_state == 3)
134 { if (i >= length) parse_state = 5;
135 else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
136 { precision = precision * 10 + s.charAt(i) - '0';
142 if (parse_state == 4)
143 { if (i >= length) parse_state = 5;
144 else fmt = s.charAt(i);
148 post = s.substring(i, length);
152 * prints a formatted number following printf conventions
153 * @param s a PrintStream
154 * @param fmt the format string
155 * @param x the double to print
158 public static void print(java.io.PrintStream s, String fmt, double x)
159 { s.print(new Format(fmt).form(x));
163 * prints a formatted number following printf conventions
164 * @param s a PrintStream
165 * @param fmt the format string
166 * @param x the long to print
168 public static void print(java.io.PrintStream s, String fmt, long x)
169 { s.print(new Format(fmt).form(x));
173 * prints a formatted number following printf conventions
174 * @param s a PrintStream
175 * @param fmt the format string
176 * @param x the character to
179 public static void print(java.io.PrintStream s, String fmt, char x)
180 { s.print(new Format(fmt).form(x));
184 * prints a formatted number following printf conventions
185 * @param s a PrintStream, fmt the format string
186 * @param x a string that represents the digits to print
189 public static void print(java.io.PrintStream s, String fmt, String x)
190 { s.print(new Format(fmt).form(x));
194 * Converts a string of digits (decimal, octal or hex) to an integer
196 * @return the numeric value of the prefix of s representing a base 10 integer
199 public static int atoi(String s)
200 { return (int)atol(s);
204 * Converts a string of digits (decimal, octal or hex) to a long integer
206 * @return the numeric value of the prefix of s representing a base 10 integer
209 public static long atol(String s)
212 while (i < s.length() && Character.isSpace(s.charAt(i))) i++;
213 if (i < s.length() && s.charAt(i) == '0')
214 { if (i + 1 < s.length() && (s.charAt(i + 1) == 'x' || s.charAt(i + 1) == 'X'))
215 return parseLong(s.substring(i + 2), 16);
216 else return parseLong(s, 8);
218 else return parseLong(s, 10);
221 private static long parseLong(String s, int base)
226 while (i < s.length() && Character.isSpace(s.charAt(i))) i++;
227 if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
228 else if (i < s.length() && s.charAt(i) == '+') { i++; }
229 while (i < s.length())
230 { char ch = s.charAt(i);
231 if ('0' <= ch && ch < '0' + base)
232 r = r * base + ch - '0';
233 else if ('A' <= ch && ch < 'A' + base - 10)
234 r = r * base + ch - 'A' + 10 ;
235 else if ('a' <= ch && ch < 'a' + base - 10)
236 r = r * base + ch - 'a' + 10 ;
245 * Converts a string of digits to an double
249 public static double atof(String s)
252 double r = 0; // integer part
253 double f = 0; // fractional part
254 double p = 1; // exponent of fractional part
255 int state = 0; // 0 = int part, 1 = frac part
257 while (i < s.length() && Character.isSpace(s.charAt(i))) i++;
258 if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
259 else if (i < s.length() && s.charAt(i) == '+') { i++; }
260 while (i < s.length())
261 { char ch = s.charAt(i);
262 if ('0' <= ch && ch <= '9')
264 r = r * 10 + ch - '0';
267 r = r + p * (ch - '0');
271 { if (state == 0) state = 1;
272 else return sign * r;
274 else if (ch == 'e' || ch == 'E')
275 { long e = (int)parseLong(s.substring(i + 1), 10);
276 return sign * r * Math.pow(10, e);
278 else return sign * r;
285 * Formats a double into a string (like sprintf in C)
286 * @param x the number to format
287 * @return the formatted string
288 * @exception IllegalArgumentException if bad argument
291 public String form(double x)
293 if (precision < 0) precision = 6;
295 if (x < 0) { x = -x; s = -1; }
298 else if (fmt == 'e' || fmt == 'E' || fmt == 'g' || fmt == 'G')
300 else throw new java.lang.IllegalArgumentException();
302 return pad(sign(s, r));
306 * Formats a long integer into a string (like sprintf in C)
307 * @param x the number to format
308 * @return the formatted string
311 public String form(long x)
314 if (fmt == 'd' || fmt == 'i')
316 if (x < 0) { x = -x; s = -1; }
320 r = convert(x, 3, 7, "01234567");
322 r = convert(x, 4, 15, "0123456789abcdef");
324 r = convert(x, 4, 15, "0123456789ABCDEF");
325 else throw new java.lang.IllegalArgumentException();
327 return pad(sign(s, r));
331 * Formats a character into a string (like sprintf in C)
332 * @param x the value to format
333 * @return the formatted string
336 public String form(char c)
338 throw new java.lang.IllegalArgumentException();
345 * Formats a string into a larger string (like sprintf in C)
346 * @param x the value to format
347 * @return the formatted string
350 public String form(String s)
352 throw new java.lang.IllegalArgumentException();
353 if (precision >= 0) s = s.substring(0, precision);
359 * a test stub for the format class
362 public static void main(String[] a)
363 { double x = 1.23456789012;
365 double z = 1.2345e30;
369 Format.print(System.out, "x = |%f|\n", x);
370 Format.print(System.out, "u = |%20f|\n", u);
371 Format.print(System.out, "x = |% .5f|\n", x);
372 Format.print(System.out, "w = |%20.5f|\n", w);
373 Format.print(System.out, "x = |%020.5f|\n", x);
374 Format.print(System.out, "x = |%+20.5f|\n", x);
375 Format.print(System.out, "x = |%+020.5f|\n", x);
376 Format.print(System.out, "x = |% 020.5f|\n", x);
377 Format.print(System.out, "y = |%#+20.5f|\n", y);
378 Format.print(System.out, "y = |%-+20.5f|\n", y);
379 Format.print(System.out, "z = |%20.5f|\n", z);
381 Format.print(System.out, "x = |%e|\n", x);
382 Format.print(System.out, "u = |%20e|\n", u);
383 Format.print(System.out, "x = |% .5e|\n", x);
384 Format.print(System.out, "w = |%20.5e|\n", w);
385 Format.print(System.out, "x = |%020.5e|\n", x);
386 Format.print(System.out, "x = |%+20.5e|\n", x);
387 Format.print(System.out, "x = |%+020.5e|\n", x);
388 Format.print(System.out, "x = |% 020.5e|\n", x);
389 Format.print(System.out, "y = |%#+20.5e|\n", y);
390 Format.print(System.out, "y = |%-+20.5e|\n", y);
392 Format.print(System.out, "x = |%g|\n", x);
393 Format.print(System.out, "z = |%g|\n", z);
394 Format.print(System.out, "w = |%g|\n", w);
395 Format.print(System.out, "u = |%g|\n", u);
396 Format.print(System.out, "y = |%.2g|\n", y);
397 Format.print(System.out, "y = |%#.2g|\n", y);
399 Format.print(System.out, "d = |%d|\n", d);
400 Format.print(System.out, "d = |%20d|\n", d);
401 Format.print(System.out, "d = |%020d|\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 = |%20.8d|\n", d);
406 Format.print(System.out, "d = |%x|\n", d);
407 Format.print(System.out, "d = |%20X|\n", d);
408 Format.print(System.out, "d = |%#20x|\n", d);
409 Format.print(System.out, "d = |%020X|\n", d);
410 Format.print(System.out, "d = |%20.8x|\n", d);
411 Format.print(System.out, "d = |%o|\n", d);
412 Format.print(System.out, "d = |%020o|\n", d);
413 Format.print(System.out, "d = |%#20o|\n", d);
414 Format.print(System.out, "d = |%#020o|\n", d);
415 Format.print(System.out, "d = |%20.12o|\n", d);
417 Format.print(System.out, "s = |%-20s|\n", "Hello");
418 Format.print(System.out, "s = |%-20c|\n", '!');
422 private static String repeat(char c, int n)
423 { if (n <= 0) return "";
424 StringBuffer s = new StringBuffer(n);
425 for (int i = 0; i < n; i++) s.append(c);
429 private static String convert(long x, int n, int m, String d)
430 { if (x == 0) return "0";
433 { r = d.charAt((int)(x & m)) + r;
439 private String pad(String r)
440 { String p = repeat(' ', width - r.length());
441 if (left_align) return pre + r + p + post;
442 else return pre + p + r + post;
445 private String sign(int s, String r)
449 { if (show_plus) p = "+";
450 else if (show_space) p = " ";
453 { if (fmt == 'o' && alternate && r.length() > 0 && r.charAt(0) != '0') p = "0";
454 else if (fmt == 'x' && alternate) p = "0x";
455 else if (fmt == 'X' && alternate) p = "0X";
460 else if ((fmt == 'd' || fmt == 'i' || fmt == 'x' || fmt == 'X' || fmt == 'o')
461 && precision > 0) w = precision;
463 return p + repeat('0', w - p.length() - r.length()) + r;
467 private String fixed_format(double d)
470 if (d > 0x7FFFFFFFFFFFFFFFL) return exp_format(d);
472 long l = (long)(precision == 0 ? d + 0.5 : d);
475 double fr = d - l; // fractional part
476 if (fr >= 1 || fr < 0) return exp_format(d);
478 return f + frac_part(fr);
481 private String frac_part(double fr)
482 // precondition: 0 <= fr < 1
486 String leading_zeroes = "";
487 for (int i = 1; i <= precision && factor <= 0x7FFFFFFFFFFFFFFFL; i++)
489 leading_zeroes = leading_zeroes + "0";
491 long l = (long) (factor * fr + 0.5);
493 z = leading_zeroes + l;
494 z = z.substring(z.length() - precision, z.length());
498 if (precision > 0 || alternate) z = "." + z;
499 if ((fmt == 'G' || fmt == 'g') && !alternate)
500 // remove trailing zeroes and decimal point
501 { int t = z.length() - 1;
502 while (t >= 0 && z.charAt(t) == '0') t--;
503 if (t >= 0 && z.charAt(t) == '.') t--;
504 z = z.substring(0, t + 1);
509 private String exp_format(double d)
514 while (dd > 10) { e++; factor /= 10; dd = dd / 10; }
515 while (dd < 1) { e--; factor *= 10; dd = dd * 10; }
516 if ((fmt == 'g' || fmt == 'G') && e >= -4 && e < precision)
517 return fixed_format(d);
520 f = f + fixed_format(d);
522 if (fmt == 'e' || fmt == 'g')
537 return f + p.substring(p.length() - 3, p.length());
541 private int precision;
544 private boolean leading_zeroes;
545 private boolean show_plus;
546 private boolean alternate;
547 private boolean show_space;
548 private boolean left_align;
549 private char fmt; // one of cdeEfgGiosxXos