Merge from the pain train
[official-gcc.git] / libjava / java / text / NumberFormat.java
blob4fc98b15c5479aca62041494b3bae3343bf01fba
1 /* NumberFormat.java -- Formats and parses numbers
2 Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA.
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
39 package java.text;
41 import java.io.IOException;
42 import java.io.InvalidObjectException;
43 import java.io.ObjectInputStream;
44 import java.io.ObjectOutputStream;
45 import java.util.Currency;
46 import java.util.Locale;
47 import java.util.MissingResourceException;
48 import java.util.ResourceBundle;
50 /**
51 * This is the abstract superclass of all classes which format and
52 * parse numeric values such as decimal numbers, integers, currency values,
53 * and percentages. These classes perform their parsing and formatting
54 * in a locale specific manner, accounting for such items as differing
55 * currency symbols and thousands separators.
56 * <p>
57 * To create an instance of a concrete subclass of <code>NumberFormat</code>,
58 * do not call a class constructor directly. Instead, use one of the
59 * static factory methods in this class such as
60 * <code>getCurrencyInstance</code>.
62 * @author Tom Tromey (tromey@cygnus.com)
63 * @author Aaron M. Renn (arenn@urbanophile.com)
64 * @date March 4, 1999
66 /* Written using "Java Class Libraries", 2nd edition, plus online
67 * API docs for JDK 1.2 from http://www.javasoft.com.
68 * Status: Believed complete and correct to 1.2, except getAvailableLocales.
70 public abstract class NumberFormat extends Format implements Cloneable
72 /**
73 * This is a constant used to create a <code>FieldPosition</code> object
74 * that will return the integer portion of a formatted number.
76 public static final int INTEGER_FIELD = 0;
78 /**
79 * This is a constant used to create a <code>FieldPosition</code> object
80 * that will return the fractional portion of a formatted number.
82 public static final int FRACTION_FIELD = 1;
84 public static class Field extends Format.Field
86 static final long serialVersionUID = 7494728892700160890L;
88 /**
89 * Attribute set to all characters containing digits of the integer
90 * part.
92 public static final NumberFormat.Field INTEGER
93 = new Field("integer");
95 /**
96 * Attribute set to all characters containing digits of the fractional
97 * part.
99 public static final NumberFormat.Field FRACTION
100 = new Field("fraction");
103 * Attribute set to all characters containing digits of the exponential
104 * part.
106 public static final NumberFormat.Field EXPONENT
107 = new Field("exponent");
110 * Attribute set to all characters containing a decimal separator.
112 public static final NumberFormat.Field DECIMAL_SEPARATOR
113 = new Field("decimal separator");
116 * Attribute set to all characters containing a sign (plus or minus).
118 public static final NumberFormat.Field SIGN
119 = new Field("sign");
122 * Attribute set to all characters containing a grouping separator (e.g.
123 * a comma, a white space,...).
125 public static final NumberFormat.Field GROUPING_SEPARATOR
126 = new Field("grouping separator");
129 * Attribute set to all characters containing an exponential symbol (e.g.
130 * 'E')
132 public static final NumberFormat.Field EXPONENT_SYMBOL
133 = new Field("exponent symbol");
136 * Attribute set to all characters containing a percent symbol (e.g. '%')
138 public static final NumberFormat.Field PERCENT
139 = new Field("percent");
142 * Attribute set to all characters containing a permille symbol.
144 public static final NumberFormat.Field PERMILLE
145 = new Field("permille");
148 * Attribute set to all characters containing the currency unit.
150 public static final NumberFormat.Field CURRENCY
151 = new Field("currency");
154 * Attribute set to all characters containing the exponent sign.
156 public static final NumberFormat.Field EXPONENT_SIGN
157 = new Field("exponent sign");
160 * Private fields to register all fields contained in this descriptor.
162 private static final NumberFormat.Field[] allFields =
164 INTEGER, FRACTION, EXPONENT, DECIMAL_SEPARATOR, SIGN,
165 GROUPING_SEPARATOR, EXPONENT_SYMBOL, PERCENT,
166 PERMILLE, CURRENCY, EXPONENT_SIGN
170 * This constructor is only used by the deserializer. Without it,
171 * it would fail to construct a valid object.
173 private Field()
175 super("");
179 * Create a Field instance with the specified field name.
181 * @param field_name Field name for the new Field instance.
183 protected Field(String field_name)
185 super (field_name);
189 * This function is used by the deserializer to know which object
190 * to use when it encounters an encoded NumberFormat.Field in a
191 * serialization stream. If the stream is valid it should return
192 * one of the above field. In the other case we throw an exception.
194 * @return a valid official NumberFormat.Field instance.
196 * @throws InvalidObjectException if the field name is invalid.
198 protected Object readResolve() throws InvalidObjectException
200 String s = getName();
201 for (int i = 0; i < allFields.length; i++)
202 if (s.equals(allFields[i].getName()))
203 return allFields[i];
205 throw new InvalidObjectException("no such NumberFormat field called "
206 + s);
211 * This method is a specialization of the format method that performs
212 * a simple formatting of the specified <code>long</code> number.
214 * @param number The <code>long</code> to format.
216 * @return The formatted number
218 public final String format (long number)
220 StringBuffer sbuf = new StringBuffer(50);
221 format (number, sbuf, null);
222 return sbuf.toString();
225 public final StringBuffer format (Object obj, StringBuffer sbuf,
226 FieldPosition pos)
228 if (obj instanceof Number)
229 return format(((Number) obj).doubleValue(), sbuf, pos);
230 else
231 throw new IllegalArgumentException
232 ("Cannot format given Object as a Number");
236 * This method formats the specified <code>double</code> and appends it to
237 * a <code>StringBuffer</code>.
239 * @param number The <code>double</code> to format.
240 * @param sb The <code>StringBuffer</code> to append the formatted number to.
241 * @param pos The desired <code>FieldPosition</code>.
243 * @return The <code>StringBuffer</code> with the appended number.
245 public abstract StringBuffer format (double number,
246 StringBuffer sbuf, FieldPosition pos);
249 * This method formats the specified <code>long</code> and appends it to
250 * a <code>StringBuffer</code>.
252 * @param number The <code>long</code> to format.
253 * @param sb The <code>StringBuffer</code> to append the formatted number to.
254 * @param pos The desired <code>FieldPosition</code>.
256 * @return The <code>StringBuffer</code> with the appended number.
258 public abstract StringBuffer format (long number,
259 StringBuffer sbuf, FieldPosition pos);
262 * This method tests the specified object for equality against this object.
263 * This will be <code>true</code> if the following conditions are met:
264 * <p>
265 * <ul>
266 * <li>The specified object is not <code>null</code>.
267 * <li>The specified object is an instance of <code>NumberFormat</code>.
268 * </ul>
269 * <p>
270 * Since this method does not test much, it is highly advised that
271 * concrete subclasses override this method.
273 * @param obj The <code>Object</code> to test against equality with
274 * this object.
276 * @return <code>true</code> if the specified object is equal to
277 * this object, <code>false</code> otherwise.
279 public boolean equals (Object obj)
281 if (! (obj instanceof NumberFormat))
282 return false;
283 NumberFormat nf = (NumberFormat) obj;
284 return (groupingUsed == nf.groupingUsed
285 && maximumFractionDigits == nf.maximumFractionDigits
286 && maximumIntegerDigits == nf.maximumIntegerDigits
287 && minimumFractionDigits == nf.minimumFractionDigits
288 && minimumIntegerDigits == nf.minimumIntegerDigits
289 && parseIntegerOnly == nf.parseIntegerOnly);
293 * This method returns a list of locales for which concrete instances
294 * of <code>NumberFormat</code> subclasses may be created.
296 * @return The list of available locales.
298 public static Locale[] getAvailableLocales ()
300 Locale[] list = new Locale[1];
301 list[0] = Locale.US;
302 return list;
305 private static NumberFormat computeInstance(Locale loc, String resource,
306 String def)
308 ResourceBundle res;
311 res = ResourceBundle.getBundle("gnu.java.locale.LocaleInformation",
312 loc, ClassLoader.getSystemClassLoader());
314 catch (MissingResourceException x)
316 res = null;
318 String fmt;
321 fmt = res == null ? def : res.getString(resource);
323 catch (MissingResourceException x)
325 fmt = def;
327 DecimalFormatSymbols dfs = new DecimalFormatSymbols (loc);
328 return new DecimalFormat (fmt, dfs);
332 * This method returns an instance of <code>NumberFormat</code> suitable
333 * for formatting and parsing currency values in the default locale.
335 * @return An instance of <code>NumberFormat</code> for handling currencies.
337 public static final NumberFormat getCurrencyInstance ()
339 return getCurrencyInstance (Locale.getDefault());
343 * This method returns an instance of <code>NumberFormat</code> suitable
344 * for formatting and parsing currency values in the specified locale.
346 * @return An instance of <code>NumberFormat</code> for handling currencies.
348 public static NumberFormat getCurrencyInstance (Locale loc)
350 return computeInstance (loc, "currencyFormat", "$#,##0.00;($#,##0.00)");
354 * This method returns a default instance for the default locale. This
355 * will be a concrete subclass of <code>NumberFormat</code>, but the
356 * actual class returned is dependent on the locale.
358 * @return An instance of the default <code>NumberFormat</code> class.
360 public static final NumberFormat getInstance ()
362 return getInstance (Locale.getDefault());
366 * This method returns a default instance for the specified locale. This
367 * will be a concrete subclass of <code>NumberFormat</code>, but the
368 * actual class returned is dependent on the locale.
370 * @param locale The desired locale.
372 * @return An instance of the default <code>NumberFormat</code> class.
374 public static NumberFormat getInstance (Locale loc)
376 // For now always return a number instance.
377 return getNumberInstance (loc);
381 * This method returns the maximum number of digits allowed in the fraction
382 * portion of a number.
384 * @return The maximum number of digits allowed in the fraction
385 * portion of a number.
387 public int getMaximumFractionDigits ()
389 return maximumFractionDigits;
393 * This method returns the maximum number of digits allowed in the integer
394 * portion of a number.
396 * @return The maximum number of digits allowed in the integer
397 * portion of a number.
399 public int getMaximumIntegerDigits ()
401 return maximumIntegerDigits;
405 * This method returns the minimum number of digits allowed in the fraction
406 * portion of a number.
408 * @return The minimum number of digits allowed in the fraction
409 * portion of a number.
411 public int getMinimumFractionDigits ()
413 return minimumFractionDigits;
417 * This method returns the minimum number of digits allowed in the integer
418 * portion of a number.
420 * @return The minimum number of digits allowed in the integer
421 * portion of a number.
423 public int getMinimumIntegerDigits ()
425 return minimumIntegerDigits;
429 * This method returns a default instance for the specified locale. This
430 * will be a concrete subclass of <code>NumberFormat</code>, but the
431 * actual class returned is dependent on the locale.
433 * @param locale The desired locale.
435 * @return An instance of the default <code>NumberFormat</code> class.
437 public static final NumberFormat getNumberInstance ()
439 return getNumberInstance (Locale.getDefault());
443 * This method returns a general purpose number formatting and parsing
444 * class for the default locale. This will be a concrete subclass of
445 * <code>NumberFormat</code>, but the actual class returned is dependent
446 * on the locale.
448 * @return An instance of a generic number formatter for the default locale.
450 public static NumberFormat getNumberInstance (Locale loc)
452 return computeInstance (loc, "numberFormat", "#,##0.###");
456 * This method returns an integer formatting and parsing class for the
457 * default locale. This will be a concrete subclass of <code>NumberFormat</code>,
458 * but the actual class returned is dependent on the locale.
460 * @return An instance of an integer number formatter for the default locale.
461 * @since 1.4
463 public static final NumberFormat getIntegerInstance()
465 return getIntegerInstance (Locale.getDefault());
469 * This method returns an integer formatting and parsing class for the
470 * default locale. This will be a concrete subclass of <code>NumberFormat</code>,
471 * but the actual class returned is dependent on the locale.
473 * @param locale the desired locale.
475 * @return An instance of an integer number formatter for the desired locale.
476 * @since 1.4
478 public static NumberFormat getIntegerInstance(Locale locale)
480 NumberFormat format = computeInstance (locale, "numberFormat", "#,##0");
481 format.setParseIntegerOnly (true);
482 return format;
486 * This method returns an instance of <code>NumberFormat</code> suitable
487 * for formatting and parsing percentage values in the default locale.
489 * @return An instance of <code>NumberFormat</code> for handling percentages.
491 public static final NumberFormat getPercentInstance ()
493 return getPercentInstance (Locale.getDefault());
497 * This method returns an instance of <code>NumberFormat</code> suitable
498 * for formatting and parsing percentage values in the specified locale.
500 * @param locale The desired locale.
502 * @return An instance of <code>NumberFormat</code> for handling percentages.
504 public static NumberFormat getPercentInstance (Locale loc)
506 return computeInstance (loc, "percentFormat", "#,##0%");
510 * This method returns a hash value for this object.
512 * @return The hash code.
514 public int hashCode ()
516 int hash = super.hashCode();
517 hash ^= (maximumFractionDigits + maximumIntegerDigits
518 + minimumFractionDigits + minimumIntegerDigits);
519 if (groupingUsed)
520 hash ^= 0xf0f0;
521 if (parseIntegerOnly)
522 hash ^= 0x0f0f;
523 return hash;
527 * This method tests whether or not grouping is in use. Grouping is
528 * a method of marking separations in numbers, such as thousand separators
529 * in the US English locale. The grouping positions and symbols are all
530 * locale specific. As an example, with grouping disabled, the number one
531 * million would appear as "1000000". With grouping enabled, this number
532 * might appear as "1,000,000". (Both of these assume the US English
533 * locale).
535 * @return <code>true</code> if grouping is enabled,
536 * <code>false</code> otherwise.
538 public boolean isGroupingUsed ()
540 return groupingUsed;
544 * This method tests whether or not only integer values should be parsed.
545 * If this class is parsing only integers, parsing stops at the decimal
546 * point.
548 * @return <code>true</code> if only integers are parsed,
549 * <code>false</code> otherwise.
551 public boolean isParseIntegerOnly ()
553 return parseIntegerOnly;
557 * This is a default constructor for use by subclasses.
559 public NumberFormat ()
564 * This method parses the specified string into a <code>Number</code>. This
565 * will be a <code>Long</code> if possible, otherwise it will be a
566 * <code>Double</code>. If no number can be parsed, no exception is
567 * thrown. Instead, the parse position remains at its initial index.
569 * @param str The string to parse.
570 * @param pp The desired <code>ParsePosition</code>.
572 * @return The parsed <code>Number</code>
574 public abstract Number parse (String sourceStr, ParsePosition pos);
577 * This method parses the specified string into a <code>Number</code>. This
578 * will be a <code>Long</code> if possible, otherwise it will be a
579 * <code>Double</code>. If no number can be parsed, an exception will be
580 * thrown.
582 * @param str The string to parse.
584 * @return The parsed <code>Number</code>
586 * @exception ParseException If no number can be parsed.
588 public Number parse (String sourceStr) throws ParseException
590 ParsePosition pp = new ParsePosition (0);
591 Number r = parse (sourceStr, pp);
592 if (r == null)
594 int index = pp.getErrorIndex();
595 if (index < 0)
596 index = pp.getIndex();
597 throw new ParseException ("couldn't parse number", index);
599 return r;
603 * This method parses the specified string into an <code>Object</code>. This
604 * will be a <code>Long</code> if possible, otherwise it will be a
605 * <code>Double</code>. If no number can be parsed, no exception is
606 * thrown. Instead, the parse position remains at its initial index.
608 * @param str The string to parse.
609 * @param pp The desired <code>ParsePosition</code>.
611 * @return The parsed <code>Object</code>
613 public final Object parseObject (String sourceStr, ParsePosition pos)
615 return parse (sourceStr, pos);
619 * This method sets the grouping behavior of this formatter. Grouping is
620 * a method of marking separations in numbers, such as thousand separators
621 * in the US English locale. The grouping positions and symbols are all
622 * locale specific. As an example, with grouping disabled, the number one
623 * million would appear as "1000000". With grouping enabled, this number
624 * might appear as "1,000,000". (Both of these assume the US English
625 * locale).
627 * @param groupingUsed <code>true</code> to enable grouping,
628 * <code>false</code> to disable it.
630 public void setGroupingUsed (boolean newValue)
632 groupingUsed = newValue;
636 * This method sets the maximum number of digits allowed in the fraction
637 * portion of a number to the specified value. If this is less than the
638 * current minimum allowed digits, the minimum allowed digits value will
639 * be lowered to be equal to the new maximum allowed digits value.
641 * @param maximumFractionDigits The new maximum fraction digits value.
643 public void setMaximumFractionDigits (int newValue)
645 maximumFractionDigits = newValue;
646 if (getMinimumFractionDigits () > maximumFractionDigits)
647 setMinimumFractionDigits (maximumFractionDigits);
651 * This method sets the maximum number of digits allowed in the integer
652 * portion of a number to the specified value. If this is less than the
653 * current minimum allowed digits, the minimum allowed digits value will
654 * be lowered to be equal to the new maximum allowed digits value.
656 * @param maximumIntegerDigits The new maximum integer digits value.
658 public void setMaximumIntegerDigits (int newValue)
660 maximumIntegerDigits = newValue;
661 if (getMinimumIntegerDigits () > maximumIntegerDigits)
662 setMinimumIntegerDigits (maximumIntegerDigits);
666 * This method sets the minimum number of digits allowed in the fraction
667 * portion of a number to the specified value. If this is greater than the
668 * current maximum allowed digits, the maximum allowed digits value will
669 * be raised to be equal to the new minimum allowed digits value.
671 * @param minimumFractionDigits The new minimum fraction digits value.
673 public void setMinimumFractionDigits (int newValue)
675 minimumFractionDigits = newValue;
676 if (getMaximumFractionDigits () < minimumFractionDigits)
677 setMaximumFractionDigits (minimumFractionDigits);
681 * This method sets the minimum number of digits allowed in the integer
682 * portion of a number to the specified value. If this is greater than the
683 * current maximum allowed digits, the maximum allowed digits value will
684 * be raised to be equal to the new minimum allowed digits value.
686 * @param minimumIntegerDigits The new minimum integer digits value.
688 public void setMinimumIntegerDigits (int newValue)
690 minimumIntegerDigits = newValue;
691 if (getMaximumIntegerDigits () < minimumIntegerDigits)
692 setMaximumIntegerDigits (minimumIntegerDigits);
695 /**
696 * This method sets the parsing behavior of this object to parse only
697 * integers or not.
699 * @param parseIntegerOnly <code>true</code> to parse only integers,
700 * <code>false</code> otherwise.
702 public void setParseIntegerOnly (boolean value)
704 parseIntegerOnly = value;
708 * This method is a specialization of the format method that performs
709 * a simple formatting of the specified <code>double</code> number.
711 * @param number The <code>double</code> to format.
713 * @return The formatted number
715 public final String format (double number)
717 StringBuffer sbuf = new StringBuffer(50);
718 format (number, sbuf, null);
719 return sbuf.toString();
722 // These field names are fixed by the serialization spec.
723 boolean groupingUsed;
724 int maximumFractionDigits;
725 private byte maxFractionDigits;
726 int maximumIntegerDigits;
727 private byte maxIntegerDigits;
728 int minimumFractionDigits;
729 private byte minFractionDigits;
730 int minimumIntegerDigits;
731 private byte minIntegerDigits;
732 boolean parseIntegerOnly;
733 private int serialVersionOnStream;
734 private static final long serialVersionUID = -2308460125733713944L;
736 private void readObject(ObjectInputStream stream)
737 throws IOException, ClassNotFoundException
739 stream.defaultReadObject();
740 if (serialVersionOnStream < 1)
742 maximumFractionDigits = maxFractionDigits;
743 maximumIntegerDigits = maxIntegerDigits;
744 minimumFractionDigits = minFractionDigits;
745 minimumIntegerDigits = minIntegerDigits;
746 serialVersionOnStream = 1;
750 private void writeObject(ObjectOutputStream stream) throws IOException
752 maxFractionDigits = maximumFractionDigits < Byte.MAX_VALUE ?
753 (byte) maximumFractionDigits : Byte.MAX_VALUE;
754 maxIntegerDigits = maximumIntegerDigits < Byte.MAX_VALUE ?
755 (byte) maximumIntegerDigits : Byte.MAX_VALUE;
756 minFractionDigits = minimumFractionDigits < Byte.MAX_VALUE ?
757 (byte) minimumFractionDigits : Byte.MAX_VALUE;
758 minIntegerDigits = minimumIntegerDigits < Byte.MAX_VALUE ?
759 (byte) minimumIntegerDigits : Byte.MAX_VALUE;
760 serialVersionOnStream = 1;
761 stream.defaultWriteObject();
765 * Returns the currency used by this number format when formatting currency
766 * values.
768 * The default implementation throws UnsupportedOperationException.
770 * @return The used currency object, or null.
772 * @throws UnsupportedOperationException If the number format class doesn't
773 * implement currency formatting.
775 * @since 1.4
777 public Currency getCurrency()
779 throw new UnsupportedOperationException();
783 * Sets the currency used by this number format when formatting currency
784 * values.
786 * The default implementation throws UnsupportedOperationException.
788 * @param currency The new currency to be used by this number format.
790 * @throws NullPointerException If currenc is null.
791 * @throws UnsupportedOperationException If the number format class doesn't
792 * implement currency formatting.
794 * @since 1.4
796 public void setCurrency(Currency currency)
798 if (currency == null)
799 throw new NullPointerException("currency may not be null");
801 throw new UnsupportedOperationException();