KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jcckit > util > FormatElement


1 /*
2  * Copyright 2003-2004, Franz-Josef Elmer, All rights reserved
3  *
4  * This library is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License as published by
6  * the Free Software Foundation; either version 2.1 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU Lesser General Public License for more details
13  * (http://www.gnu.org/copyleft/lesser.html).
14  *
15  * You should have received a copy of the GNU Lesser General Public License
16  * along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  */

19 package jcckit.util;
20
21 /**
22  *
23  *
24  * @author Franz-Josef Elmer
25  */

26 class FormatElement {
27   /** All descriptor characters. */
28   static final String JavaDoc DESCRIPTORS = "doxfeEgG";
29   private static final String JavaDoc INT_DESCRIPTORS = "dox";
30   private static final int INT_DESCRIPTOR = 0;
31   private static final int FLOAT_DESCRIPTOR = 1;
32   /**
33    * Calculate the integer power of a floating point number.
34    * @param n Exponent.
35    * @param x Number.
36    * @return <tt>x^n</tt>.
37    */

38   private static final double power(double x, int n) {
39     return n < 0 ? 1.0 / power2(x, -n) : power2(x, n);
40   }
41
42   /** Calculate <tt>x^n</tt> recursively assuming <tt>n > 0</tt>. */
43   private static final double power2(double x, int n) {
44     switch (n) {
45     case 0: return 1;
46     case 1: return x;
47     default:
48       double p = power2(x, n / 2);
49       return p * p * power2(x, n % 2);
50     }
51   }
52
53   private final char _descriptor;
54   private final int _descriptorType;
55   private final double _tenToPrecision;
56   private boolean _decimalPoint;
57   private boolean _flushLeft;
58   private boolean _leadingZeros;
59   private boolean _alwaysSign;
60   private int _width;
61   private int _precision;
62
63   /** Creates an instance for the specified format string. */
64   FormatElement(String JavaDoc formatString) {
65     int len = formatString.length() - 1;
66     _descriptor = formatString.charAt(len);
67     if (DESCRIPTORS.indexOf(_descriptor) < 0) {
68       throw new IllegalArgumentException JavaDoc("Format element '" + formatString
69           + "' does not ends with one of the following characters: "
70           + DESCRIPTORS);
71     }
72     _descriptorType = INT_DESCRIPTORS.indexOf(_descriptor) >= 0
73                                 ? INT_DESCRIPTOR : FLOAT_DESCRIPTOR;
74     if (formatString.length() > 1) {
75       switch (formatString.charAt(0)) {
76       case '-':
77         _flushLeft = true;
78         formatString = formatString.substring(1);
79         break;
80       case '0':
81         _leadingZeros = true;
82         formatString = formatString.substring(1);
83         break;
84       case '+':
85         _alwaysSign = true;
86         formatString = formatString.substring(1);
87         break;
88       }
89       len = formatString.length() - 1;
90       int index = formatString.indexOf('.');
91       _decimalPoint = index >= 0;
92       int last = _decimalPoint ? index : len;
93       if (last > 0) {
94         _width = Integer.parseInt(formatString.substring(0, last));
95       }
96       if (_decimalPoint) {
97         index++;
98         if (index < len) {
99           _precision = Integer.parseInt(formatString.substring(index, len));
100         }
101       }
102     }
103     _tenToPrecision = power(10, _precision);
104   }
105
106   /**
107    * Format a number in accordance of the format string
108    * given at the initialisation of this instance.
109    * @param buffer Buffer to which the formated output will be appended.
110    * @param number Number to be formated.
111    */

112   public void form(StringBuffer JavaDoc buffer, long number) {
113     if (_descriptorType == FLOAT_DESCRIPTOR) {
114       form(buffer, (double) number);
115     } else {
116       // Format absolut value in the right base
117
buffer.append(form(number < 0,
118                          Long.toString(Math.abs(number),
119                                 _descriptor == 'o' ? 8
120                                           : (_descriptor == 'x' ? 16 : 10)),
121                          ""));
122     }
123   }
124
125   /**
126    * Format a number in accordance of the format string
127    * given at the initialisation of this instance.
128    * @param buffer Buffer to which the formated output will be appended.
129    * @param number Number to be formated.
130    */

131   public void form(StringBuffer JavaDoc buffer, double number) {
132     if (_descriptorType == INT_DESCRIPTOR) {
133       form(buffer, (long) Math.floor(number + 0.5));
134     } else if (_descriptor == 'f') {
135       buffer.append(formF(number));
136     } else if (_descriptor == 'e' || _descriptor == 'E') {
137       buffer.append(formE(number));
138     } else if (_descriptor == 'g' || _descriptor == 'G') {
139       String JavaDoc formF = formF(number);
140       String JavaDoc formE = formE(number);
141       buffer.append(formF.length() > formE.length() ? formE : formF);
142     }
143   }
144
145   private String JavaDoc form(boolean negativeValue, String JavaDoc intPart, String JavaDoc fracPart) {
146     int len = intPart.length() + fracPart.length();
147
148     // Buffer holding the result
149
StringBuffer JavaDoc result = new StringBuffer JavaDoc();
150     int count = 0;
151
152     // add sign if necessary
153
if (_alwaysSign || negativeValue) {
154       result.append(negativeValue ? '-' : '+');
155       count++;
156     }
157
158     // add zeros if necessary
159
if (_leadingZeros) {
160       for (int i = count + len; i < _width; i++) {
161         result.append('0');
162         count++;
163       }
164     }
165
166     // add number
167
result.append(intPart).append(fracPart);
168     count += len;
169
170     // add spaces if necessary
171
if (_flushLeft) {
172       for (; count < _width; count++) {
173         result.append(' ');
174       }
175     } else {
176       for (; count < _width; count++) {
177         result.insert(0, ' ');
178       }
179     }
180
181     return new String JavaDoc(result);
182   }
183
184   /** Format floating point number with exponent. */
185   private String JavaDoc formE(double number) {
186     // format absolute mantisse
187
int exponent = 0;
188     String JavaDoc zeros = "00000000000000000000000".substring(0, _precision + 1);
189     if (number != 0) {
190       exponent = (int) Math.floor(Math.log(Math.abs(number)) / Math.log(10));
191       double mantisse = Math.floor(Math.abs(number * power(10.0,
192                                             _precision - exponent)) + 0.5);
193       if (mantisse >= 10 * _tenToPrecision) {
194         exponent++;
195         mantisse = Math.floor(Math.abs(number * power(10.0,
196                                           _precision - exponent)) + 0.5);
197       }
198       zeros = Long.toString((long) mantisse);
199     }
200
201     // make fractional part
202
StringBuffer JavaDoc fracPart = new StringBuffer JavaDoc();
203     if (_decimalPoint) {
204       fracPart.append('.').append(zeros.substring(1));
205     }
206
207     // make exponent
208
fracPart.append(Character.isLowerCase(_descriptor) ? 'e': 'E')
209             .append(exponent < 0 ? '-' : '+');
210     exponent = Math.abs(exponent);
211     for (int i = 0, n = fracPart.length(); i < 3; i++) {
212       fracPart.insert(n, Character.forDigit(exponent % 10, 10));
213       exponent /= 10;
214     }
215
216     return form(number < 0, zeros.substring(0, 1), new String JavaDoc(fracPart));
217   }
218
219   /** Format floating point number. */
220   private String JavaDoc formF(double number) {
221     // Format absolut value
222
double multiplier = number < 0 ? - _tenToPrecision : _tenToPrecision;
223     String JavaDoc digits
224         = Long.toString((long) Math.floor(number * multiplier + 0.5));
225     String JavaDoc intPart = digits;
226     StringBuffer JavaDoc fracPart = new StringBuffer JavaDoc();
227     if (_decimalPoint) {
228       int len = digits.length() - _precision;
229       fracPart.append('.').append(digits.substring(Math.max(0, len)));
230       if (len > 0) {
231         intPart = digits.substring(0, len);
232       } else {
233         intPart = "0";
234         for (; len < 0; len++) {
235           fracPart.insert(1, '0');
236         }
237       }
238     }
239
240     return form(number < 0, intPart, new String JavaDoc(fracPart));
241   }
242 }
243
Popular Tags