- /*
- * @(#)DecimalFormat.java 1.71 03/01/23
- *
- * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
- * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
- */
- /*
- * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
- * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
- *
- * The original version of this source code and documentation is copyrighted
- * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
- * materials are provided under terms of a License Agreement between Taligent
- * and Sun. This technology is protected by multiple US and International
- * patents. This notice and attribution to Taligent may not be removed.
- * Taligent is a registered trademark of Taligent, Inc.
- *
- */
- package java.text;
- import java.io.InvalidObjectException;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.math.BigInteger;
- import java.util.ArrayList;
- import java.util.Currency;
- import java.util.Hashtable;
- import java.util.Locale;
- import java.util.ResourceBundle;
- import sun.text.resources.LocaleData;
- /**
- * <code>DecimalFormat</code> is a concrete subclass of
- * <code>NumberFormat</code> that formats decimal numbers. It has a variety of
- * features designed to make it possible to parse and format numbers in any
- * locale, including support for Western, Arabic, and Indic digits. It also
- * supports different kinds of numbers, including integers (123), fixed-point
- * numbers (123.4), scientific notation (1.23E4), percentages (12%), and
- * currency amounts ($123). All of these can be localized.
- *
- * <p>To obtain a <code>NumberFormat</code> for a specific locale, including the
- * default locale, call one of <code>NumberFormat</code>'s factory methods, such
- * as <code>getInstance()</code>. In general, do not call the
- * <code>DecimalFormat</code> constructors directly, since the
- * <code>NumberFormat</code> factory methods may return subclasses other than
- * <code>DecimalFormat</code>. If you need to customize the format object, do
- * something like this:
- *
- * <blockquote><pre>
- * NumberFormat f = NumberFormat.getInstance(loc);
- * if (f instanceof DecimalFormat) {
- * ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
- * }
- * </pre></blockquote>
- *
- * <p>A <code>DecimalFormat</code> comprises a <em>pattern</em> and a set of
- * <em>symbols</em>. The pattern may be set directly using
- * <code>applyPattern()</code>, or indirectly using the API methods. The
- * symbols are stored in a <code>DecimalFormatSymbols</code> object. When using
- * the <code>NumberFormat</code> factory methods, the pattern and symbols are
- * read from localized <code>ResourceBundle</code>s.
- *
- * <h4>Patterns</h4>
- *
- * <code>DecimalFormat</code> patterns have the following syntax:
- * <blockquote><pre>
- * <i>Pattern:</i>
- * <i>PositivePattern</i>
- * <i>PositivePattern</i> ; <i>NegativePattern</i>
- * <i>PositivePattern:</i>
- * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
- * <i>NegativePattern:</i>
- * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
- * <i>Prefix:</i>
- * any Unicode characters except \uFFFE, \uFFFF, and special characters
- * <i>Suffix:</i>
- * any Unicode characters except \uFFFE, \uFFFF, and special characters
- * <i>Number:</i>
- * <i>Integer</i> <i>Exponent<sub>opt</sub></i>
- * <i>Integer</i> . <i>Fraction</i> <i>Exponent<sub>opt</sub></i>
- * <i>Integer:</i>
- * <i>MinimumInteger</i>
- * #
- * # <i>Integer</i>
- * # , <i>Integer</i>
- * <i>MinimumInteger:</i>
- * 0
- * 0 <i>MinimumInteger</i>
- * 0 , <i>MinimumInteger</i>
- * <i>Fraction:</i>
- * <i>MinimumFraction<sub>opt</sub></i> <i>OptionalFraction<sub>opt</sub></i>
- * <i>MinimumFraction:</i>
- * 0 <i>MinimumFraction<sub>opt</sub></i>
- * <i>OptionalFraction:</i>
- * # <i>OptionalFraction<sub>opt</sub></i>
- * <i>Exponent:</i>
- * E <i>MinimumExponent</i>
- * <i>MinimumExponent:</i>
- * 0 <i>MinimumExponent<sub>opt</sub></i>
- * </pre></blockquote>
- *
- * <p>A <code>DecimalFormat</code> pattern contains a positive and negative
- * subpattern, for example, <code>"#,##0.00;(#,##0.00)"</code>. Each
- * subpattern has a prefix, numeric part, and suffix. The negative subpattern
- * is optional; if absent, then the positive subpattern prefixed with the
- * localized minus sign (code>'-'</code> in most locales) is used as the
- * negative subpattern. That is, <code>"0.00"</code> alone is equivalent to
- * <code>"0.00;-0.00"</code>. If there is an explicit negative subpattern, it
- * serves only to specify the negative prefix and suffix; the number of digits,
- * minimal digits, and other characteristics are all the same as the positive
- * pattern. That means that <code>"#,##0.0#;(#)"</code> produces precisely
- * the same behavior as <code>"#,##0.0#;(#,##0.0#)"</code>.
- *
- * <p>The prefixes, suffixes, and various symbols used for infinity, digits,
- * thousands separators, decimal separators, etc. may be set to arbitrary
- * values, and they will appear properly during formatting. However, care must
- * be taken that the symbols and strings do not conflict, or parsing will be
- * unreliable. For example, either the positive and negative prefixes or the
- * suffixes must be distinct for <code>DecimalFormat.parse()</code> to be able
- * to distinguish positive from negative values. (If they are identical, then
- * <code>DecimalFormat</code> will behave as if no negative subpattern was
- * specified.) Another example is that the decimal separator and thousands
- * separator should be distinct characters, or parsing will be impossible.
- *
- * <p>The grouping separator is commonly used for thousands, but in some
- * countries it separates ten-thousands. The grouping size is a constant number
- * of digits between the grouping characters, such as 3 for 100,000,000 or 4 for
- * 1,0000,0000. If you supply a pattern with multiple grouping characters, the
- * interval between the last one and the end of the integer is the one that is
- * used. So <code>"#,##,###,####"</code> == <code>"######,####"</code> ==
- * <code>"##,####,####"</code>.
- *
- * <h4>Special Pattern Characters</h4>
- *
- * <p>Many characters in a pattern are taken literally; they are matched during
- * parsing and output unchanged during formatting. Special characters, on the
- * other hand, stand for other characters, strings, or classes of characters.
- * They must be quoted, unless noted otherwise, if they are to appear in the
- * prefix or suffix as literals.
- *
- * <p>The characters listed here are used in non-localized patterns. Localized
- * patterns use the corresponding characters taken from this formatter's
- * <code>DecimalFormatSymbols</code> object instead, and these characters lose
- * their special status. Two exceptions are the currency sign and quote, which
- * are not localized.
- *
- * <blockquote>
- * <table border=0 cellspacing=3 cellpadding=0 summary="Chart showing symbol,
- * location, localized, and meaning.">
- * <tr bgcolor="#ccccff">
- * <th align=left>Symbol
- * <th align=left>Location
- * <th align=left>Localized?
- * <th align=left>Meaning
- * <tr valign=top>
- * <td><code>0</code>
- * <td>Number
- * <td>Yes
- * <td>Digit
- * <tr valign=top bgcolor="#eeeeff">
- * <td><code>#</code>
- * <td>Number
- * <td>Yes
- * <td>Digit, zero shows as absent
- * <tr valign=top>
- * <td><code>.</code>
- * <td>Number
- * <td>Yes
- * <td>Decimal separator or monetary decimal separator
- * <tr valign=top bgcolor="#eeeeff">
- * <td><code>-</code>
- * <td>Number
- * <td>Yes
- * <td>Minus sign
- * <tr valign=top>
- * <td><code>,</code>
- * <td>Number
- * <td>Yes
- * <td>Grouping separator
- * <tr valign=top bgcolor="#eeeeff">
- * <td><code>E</code>
- * <td>Number
- * <td>Yes
- * <td>Separates mantissa and exponent in scientific notation.
- * <em>Need not be quoted in prefix or suffix.</em>
- * <tr valign=top>
- * <td><code></code>
- * <td>Subpattern boundary
- * <td>Yes
- * <td>Separates positive and negative subpatterns
- * <tr valign=top bgcolor="#eeeeff">
- * <td><code>%</code>
- * <td>Prefix or suffix
- * <td>Yes
- * <td>Multiply by 100 and show as percentage
- * <tr valign=top>
- * <td><code>\u2030</code>
- * <td>Prefix or suffix
- * <td>Yes
- * <td>Multiply by 1000 and show as per mille
- * <tr valign=top bgcolor="#eeeeff">
- * <td><code>¤</code> (<code>\u00A4</code>)
- * <td>Prefix or suffix
- * <td>No
- * <td>Currency sign, replaced by currency symbol. If
- * doubled, replaced by international currency symbol.
- * If present in a pattern, the monetary decimal separator
- * is used instead of the decimal separator.
- * <tr valign=top>
- * <td><code>'</code>
- * <td>Prefix or suffix
- * <td>No
- * <td>Used to quote special characters in a prefix or suffix,
- * for example, <code>"'#'#"</code> formats 123 to
- * <code>"#123"</code>. To create a single quote
- * itself, use two in a row: <code>"# o''clock"</code>.
- * </table>
- * </blockquote>
- *
- * <h4>Scientific Notation</h4>
- *
- * <p>Numbers in scientific notation are expressed as the product of a mantissa
- * and a power of ten, for example, 1234 can be expressed as 1.234 x 10^3. The
- * mantissa is often in the range 1.0 <= x < 10.0, but it need not be.
- * <code>DecimalFormat</code> can be instructed to format and parse scientific
- * notation <em>only via a pattern</em> there is currently no factory method
- * that creates a scientific notation format. In a pattern, the exponent
- * character immediately followed by one or more digit characters indicates
- * scientific notation. Example: <code>"0.###E0"</code> formats the number
- * 1234 as <code>"1.234E3"</code>.
- *
- * <ul>
- * <li>The number of digit characters after the exponent character gives the
- * minimum exponent digit count. There is no maximum. Negative exponents are
- * formatted using the localized minus sign, <em>not</em> the prefix and suffix
- * from the pattern. This allows patterns such as <code>"0.###E0 m/s"</code>.
- *
- * <li>The minimum and maximum number of integer digits are interpreted
- * together:
- *
- * <ul>
- * <li>If the maximum number of integer digits is greater than their minimum number
- * and greater than 1, it forces the exponent to be a multiple of the maximum
- * number of integer digits, and the minimum number of integer digits to be
- * interpreted as 1. The most common use of this is to generate
- * <em>engineering notation</em>, in which the exponent is a multiple of three,
- * e.g., <code>"##0.#####E0"</code>. Using this pattern, the number 12345
- * formats to <code>"12.345E3"</code>, and 123456 formats to
- * <code>"123.456E3"</code>.
- *
- * <li>Otherwise, the minimum number of integer digits is achieved by adjusting the
- * exponent. Example: 0.00123 formatted with <code>"00.###E0"</code> yields
- * <code>"12.3E-4"</code>.
- * </ul>
- *
- * <li>The number of significant digits in the mantissa is the sum of the
- * <em>minimum integer</em> and <em>maximum fraction</em> digits, and is
- * unaffected by the maximum integer digits. For example, 12345 formatted with
- * <code>"##0.##E0"</code> is <code>"12.3E3"</code>. To show all digits, set
- * the significant digits count to zero. The number of significant digits
- * does not affect parsing.
- *
- * <li>Exponential patterns may not contain grouping separators.
- * </ul>
- *
- * <h4>Rounding</h4>
- *
- * <code>DecimalFormat</code> uses half-even rounding (see
- * {@link java.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for
- * formatting.
- *
- * <h4>Digits</h4>
- *
- * For formatting, <code>DecimalFormat</code> uses the ten consecutive
- * characters starting with the localized zero digit defined in the
- * <code>DecimalFormatSymbols</code> object as digits. For parsing, these
- * digits as well as all Unicode decimal digits, as defined by
- * {@link Character#digit Character.digit}, are recognized.
- *
- * <h4>Special Values</h4>
- *
- * <p><code>NaN</code> is formatted as a single character, typically
- * <code>\uFFFD</code>. This character is determined by the
- * <code>DecimalFormatSymbols</code> object. This is the only value for which
- * the prefixes and suffixes are not used.
- *
- * <p>Infinity is formatted as a single character, typically
- * <code>\u221E</code>, with the positive or negative prefixes and suffixes
- * applied. The infinity character is determined by the
- * <code>DecimalFormatSymbols</code> object.
- *
- * <p>Negative zero (<code>"-0"</code>) parses to <code>Double(-0.0)</code>,
- * unless <code>isParseIntegerOnly()</code> is true, in which case it parses to
- * <code>Long(0)</code>.
- *
- * <h4><a name="synchronization">Synchronization</a></h4>
- *
- * <p>
- * Decimal formats are generally not synchronized.
- * It is recommended to create separate format instances for each thread.
- * If multiple threads access a format concurrently, it must be synchronized
- * externally.
- *
- * <h4>Example</h4>
- *
- * <blockquote><pre>
- * <strong>// Print out a number using the localized number, integer, currency,
- * // and percent format for each locale</strong>
- * Locale[] locales = NumberFormat.getAvailableLocales();
- * double myNumber = -1234.56;
- * NumberFormat form;
- * for (int j=0; j<4; ++j) {
- * System.out.println("FORMAT");
- * for (int i = 0; i < locales.length; ++i) {
- * if (locales[i].getCountry().length() == 0) {
- * continue; // Skip language-only locales
- * }
- * System.out.print(locales[i].getDisplayName());
- * switch (j) {
- * case 0:
- * form = NumberFormat.getInstance(locales[i]); break;
- * case 1:
- * form = NumberFormat.getIntegerInstance(locales[i]); break;
- * case 2:
- * form = NumberFormat.getCurrencyInstance(locales[i]); break;
- * default:
- * form = NumberFormat.getPercentInstance(locales[i]); break;
- * }
- * if (form instanceof DecimalFormat) {
- * System.out.print(": " + ((DecimalFormat) form).toPattern());
- * }
- * System.out.print(" -> " + form.format(myNumber));
- * try {
- * System.out.println(" -> " + form.parse(form.format(myNumber)));
- * } catch (ParseException e) {}
- * }
- * }
- * </pre></blockquote>
- *
- * @see <a href="http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html">Java Tutorial</a>
- * @see NumberFormat
- * @see DecimalFormatSymbols
- * @see ParsePosition
- * @version 1.71 01/23/03
- * @author Mark Davis
- * @author Alan Liu
- */
- public class DecimalFormat extends NumberFormat {
- /**
- * Creates a DecimalFormat using the default pattern and symbols
- * for the default locale. This is a convenient way to obtain a
- * DecimalFormat when internationalization is not the main concern.
- * <p>
- * To obtain standard formats for a given locale, use the factory methods
- * on NumberFormat such as getNumberInstance. These factories will
- * return the most appropriate sub-class of NumberFormat for a given
- * locale.
- *
- * @see java.text.NumberFormat#getInstance
- * @see java.text.NumberFormat#getNumberInstance
- * @see java.text.NumberFormat#getCurrencyInstance
- * @see java.text.NumberFormat#getPercentInstance
- */
- public DecimalFormat() {
- Locale def = Locale.getDefault();
- // try to get the pattern from the cache
- String pattern = (String) cachedLocaleData.get(def);
- if (pattern == null) { /* cache miss */
- // Get the pattern for the default locale.
- ResourceBundle rb = LocaleData.getLocaleElements(def);
- String[] all = rb.getStringArray("NumberPatterns");
- pattern = all[0];
- /* update cache */
- cachedLocaleData.put(def, pattern);
- }
- // Always applyPattern after the symbols are set
- this.symbols = new DecimalFormatSymbols(def);
- applyPattern(pattern, false);
- }
- /**
- * Creates a DecimalFormat using the given pattern and the symbols
- * for the default locale. This is a convenient way to obtain a
- * DecimalFormat when internationalization is not the main concern.
- * <p>
- * To obtain standard formats for a given locale, use the factory methods
- * on NumberFormat such as getNumberInstance. These factories will
- * return the most appropriate sub-class of NumberFormat for a given
- * locale.
- *
- * @param pattern A non-localized pattern string.
- * @exception NullPointerException if <code>pattern</code> is null
- * @exception IllegalArgumentException if the given pattern is invalid.
- * @see java.text.NumberFormat#getInstance
- * @see java.text.NumberFormat#getNumberInstance
- * @see java.text.NumberFormat#getCurrencyInstance
- * @see java.text.NumberFormat#getPercentInstance
- */
- public DecimalFormat(String pattern) {
- // Always applyPattern after the symbols are set
- this.symbols = new DecimalFormatSymbols(Locale.getDefault());
- applyPattern(pattern, false);
- }
- /**
- * Creates a DecimalFormat using the given pattern and symbols.
- * Use this constructor when you need to completely customize the
- * behavior of the format.
- * <p>
- * To obtain standard formats for a given
- * locale, use the factory methods on NumberFormat such as
- * getInstance or getCurrencyInstance. If you need only minor adjustments
- * to a standard format, you can modify the format returned by
- * a NumberFormat factory method.
- *
- * @param pattern a non-localized pattern string
- * @param symbols the set of symbols to be used
- * @exception NullPointerException if any of the given arguments is null
- * @exception IllegalArgumentException if the given pattern is invalid
- * @see java.text.NumberFormat#getInstance
- * @see java.text.NumberFormat#getNumberInstance
- * @see java.text.NumberFormat#getCurrencyInstance
- * @see java.text.NumberFormat#getPercentInstance
- * @see java.text.DecimalFormatSymbols
- */
- public DecimalFormat (String pattern, DecimalFormatSymbols symbols) {
- // Always applyPattern after the symbols are set
- this.symbols = (DecimalFormatSymbols)symbols.clone();
- applyPattern(pattern, false);
- }
- // Overrides
- /**
- * Formats a double to produce a string.
- * @param number The double to format
- * @param result where the text is to be appended
- * @param fieldPosition On input: an alignment field, if desired.
- * On output: the offsets of the alignment field.
- * @return The formatted number string
- * @see java.text.FieldPosition
- */
- public StringBuffer format(double number, StringBuffer result,
- FieldPosition fieldPosition)
- {
- fieldPosition.setBeginIndex(0);
- fieldPosition.setEndIndex(0);
- return format(number, result, fieldPosition.getFieldDelegate());
- }
- /**
- * Formats a double to produce a string.
- * @param number The double to format
- * @param result where the text is to be appended
- * @param delegate notified of locations of sub fields
- * @return The formatted number string
- */
- private StringBuffer format(double number, StringBuffer result,
- FieldDelegate delegate) {
- if (Double.isNaN(number))
- {
- int iFieldStart = result.length();
- result.append(symbols.getNaN());
- delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
- iFieldStart, result.length(), result);
- return result;
- }
- /* Detecting whether a double is negative is easy with the exception of
- * the value -0.0. This is a double which has a zero mantissa (and
- * exponent), but a negative sign bit. It is semantically distinct from
- * a zero with a positive sign bit, and this distinction is important
- * to certain kinds of computations. However, it's a little tricky to
- * detect, since (-0.0 == 0.0) and !(-0.0 < 0.0). How then, you may
- * ask, does it behave distinctly from +0.0? Well, 1/(-0.0) ==
- * -Infinity. Proper detection of -0.0 is needed to deal with the
- * issues raised by bugs 4106658, 4106667, and 4147706. Liu 7/6/98.
- */
- boolean isNegative = (number < 0.0) || (number == 0.0 && 1/number < 0.0);
- if (isNegative) number = -number;
- // Do this BEFORE checking to see if value is infinite!
- if (multiplier != 1) number *= multiplier;
- if (Double.isInfinite(number))
- {
- if (isNegative) {
- append(result, negativePrefix, delegate,
- getNegativePrefixFieldPositions(), Field.SIGN);
- }
- else {
- append(result, positivePrefix, delegate,
- getPositivePrefixFieldPositions(), Field.SIGN);
- }
- int iFieldStart = result.length();
- result.append(symbols.getInfinity());
- delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
- iFieldStart, result.length(), result);
- if (isNegative) {
- append(result, negativeSuffix, delegate,
- getNegativeSuffixFieldPositions(), Field.SIGN);
- }
- else {
- append(result, positiveSuffix, delegate,
- getPositiveSuffixFieldPositions(), Field.SIGN);
- }
- return result;
- }
- // At this point we are guaranteed a nonnegative finite
- // number.
- synchronized(digitList) {
- digitList.set(number, useExponentialNotation ?
- getMaximumIntegerDigits() + getMaximumFractionDigits() :
- getMaximumFractionDigits(),
- !useExponentialNotation);
- return subformat(result, delegate, isNegative, false);
- }
- }
- /**
- * Format a long to produce a string.
- * @param number The long to format
- * @param result where the text is to be appended
- * @param fieldPosition On input: an alignment field, if desired.
- * On output: the offsets of the alignment field.
- * @return The formatted number string
- * @see java.text.FieldPosition
- */
- public StringBuffer format(long number, StringBuffer result,
- FieldPosition fieldPosition)
- {
- fieldPosition.setBeginIndex(0);
- fieldPosition.setEndIndex(0);
- return format(number, result, fieldPosition.getFieldDelegate());
- }
- /**
- * Format a long to produce a string.
- * @param number The long to format
- * @param result where the text is to be appended
- * @param delegate notified of locations of sub fields
- * @return The formatted number string
- * @see java.text.FieldPosition
- */
- private StringBuffer format(long number, StringBuffer result,
- FieldDelegate delegate) {
- boolean isNegative = (number < 0);
- if (isNegative) number = -number;
- // In general, long values always represent real finite numbers, so
- // we don't have to check for +/- Infinity or NaN. However, there
- // is one case we have to be careful of: The multiplier can push
- // a number near MIN_VALUE or MAX_VALUE outside the legal range. We
- // check for this before multiplying, and if it happens we use doubles
- // instead, trading off accuracy for range.
- if (multiplier != 1 && multiplier != 0)
- {
- boolean useDouble = false;
- if (number < 0) // This can only happen if number == Long.MIN_VALUE
- {
- long cutoff = Long.MIN_VALUE / multiplier;
- useDouble = (number < cutoff);
- }
- else
- {
- long cutoff = Long.MAX_VALUE / multiplier;
- useDouble = (number > cutoff);
- }
- if (useDouble)
- {
- double dnumber = (double)(isNegative ? -number : number);
- return format(dnumber, result, delegate);
- }
- }
- number *= multiplier;
- synchronized(digitList) {
- digitList.set(number, useExponentialNotation ?
- getMaximumIntegerDigits() + getMaximumFractionDigits() : 0);
- return subformat(result, delegate, isNegative, true);
- }
- }
- /**
- * Formats an Object producing an <code>AttributedCharacterIterator</code>.
- * You can use the returned <code>AttributedCharacterIterator</code>
- * to build the resulting String, as well as to determine information
- * about the resulting String.
- * <p>
- * Each attribute key of the AttributedCharacterIterator will be of type
- * <code>NumberFormat.Field</code>, with the attribute value being the
- * same as the attribute key.
- *
- * @exception NullPointerException if obj is null.
- * @exception IllegalArgumentException when the Format cannot format the
- * given object.
- * @param obj The object to format
- * @return AttributedCharacterIterator describing the formatted value.
- * @since 1.4
- */
- public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
- CharacterIteratorFieldDelegate delegate =
- new CharacterIteratorFieldDelegate();
- StringBuffer sb = new StringBuffer();
- if (obj instanceof Long ||
- (obj instanceof BigInteger &&
- ((BigInteger)obj).bitLength() < 64)) {
- format(((Number)obj).longValue(), sb, delegate);
- }
- else if (obj == null) {
- throw new NullPointerException(
- "formatToCharacterIterator must be passed non-null object");
- }
- else if (obj instanceof Number) {
- format(((Number)obj).doubleValue(), sb, delegate);
- }
- else {
- throw new IllegalArgumentException(
- "Cannot format given Object as a Number");
- }
- return delegate.getIterator(sb.toString());
- }
- /**
- * Complete the formatting of a finite number. On entry, the digitList must
- * be filled in with the correct digits.
- */
- private StringBuffer subformat(StringBuffer result, FieldDelegate delegate,
- boolean isNegative, boolean isInteger)
- {
- // NOTE: This isn't required anymore because DigitList takes care of this.
- //
- // // The negative of the exponent represents the number of leading
- // // zeros between the decimal and the first non-zero digit, for
- // // a value < 0.1 (e.g., for 0.00123, -fExponent == 2). If this
- // // is more than the maximum fraction digits, then we have an underflow
- // // for the printed representation. We recognize this here and set
- // // the DigitList representation to zero in this situation.
- //
- // if (-digitList.decimalAt >= getMaximumFractionDigits())
- // {
- // digitList.count = 0;
- // }
- char zero = symbols.getZeroDigit();
- int zeroDelta = zero - '0'; // '0' is the DigitList representation of zero
- char grouping = symbols.getGroupingSeparator();
- char decimal = isCurrencyFormat ?
- symbols.getMonetaryDecimalSeparator() :
- symbols.getDecimalSeparator();
- /* Per bug 4147706, DecimalFormat must respect the sign of numbers which
- * format as zero. This allows sensible computations and preserves
- * relations such as signum(1/x) = signum(x), where x is +Infinity or
- * -Infinity. Prior to this fix, we always formatted zero values as if
- * they were positive. Liu 7/6/98.
- */
- if (digitList.isZero())
- {
- digitList.decimalAt = 0; // Normalize
- }
- int fieldStart = result.length();
- if (isNegative) {
- append(result, negativePrefix, delegate,
- getNegativePrefixFieldPositions(), Field.SIGN);
- }
- else {
- append(result, positivePrefix, delegate,
- getPositivePrefixFieldPositions(), Field.SIGN);
- }
- if (useExponentialNotation)
- {
- int iFieldStart = result.length();
- int iFieldEnd = -1;
- int fFieldStart = -1;
- // Minimum integer digits are handled in exponential format by
- // adjusting the exponent. For example, 0.01234 with 3 minimum
- // integer digits is "123.4E-4".
- // Maximum integer digits are interpreted as indicating the
- // repeating range. This is useful for engineering notation, in
- // which the exponent is restricted to a multiple of 3. For
- // example, 0.01234 with 3 maximum integer digits is "12.34e-3".
- // If maximum integer digits are > 1 and are larger than
- // minimum integer digits, then minimum integer digits are
- // ignored.
- int exponent = digitList.decimalAt;
- int repeat = getMaximumIntegerDigits();
- int minimumIntegerDigits = getMinimumIntegerDigits();
- if (repeat > 1 && repeat > minimumIntegerDigits) {
- // A repeating range is defined; adjust to it as follows.
- // If repeat == 3, we have 6,5,4=>3; 3,2,1=>0; 0,-1,-2=>-3;
- // -3,-4,-5=>-6, etc. This takes into account that the
- // exponent we have here is off by one from what we expect;
- // it is for the format 0.MMMMMx10^n.
- if (exponent >= 1) {
- exponent = ((exponent - 1) / repeat) * repeat;
- } else {
- // integer division rounds towards 0
- exponent = ((exponent - repeat) / repeat) * repeat;
- }
- minimumIntegerDigits = 1;
- }
- else
- {
- // No repeating range is defined; use minimum integer digits.
- exponent -= minimumIntegerDigits;
- }
- // We now output a minimum number of digits, and more if there
- // are more digits, up to the maximum number of digits. We
- // place the decimal point after the "integer" digits, which
- // are the first (decimalAt - exponent) digits.
- int minimumDigits = getMinimumIntegerDigits()
- + getMinimumFractionDigits();
- // The number of integer digits is handled specially if the number
- // is zero, since then there may be no digits.
- int integerDigits = digitList.isZero() ? minimumIntegerDigits :
- digitList.decimalAt - exponent;
- if (minimumDigits < integerDigits) {
- minimumDigits = integerDigits;
- }
- int totalDigits = digitList.count;
- if (minimumDigits > totalDigits) totalDigits = minimumDigits;
- boolean addedDecimalSeparator = false;
- for (int i=0; i<totalDigits; ++i)
- {
- if (i == integerDigits)
- {
- // Record field information for caller.
- iFieldEnd = result.length();
- result.append(decimal);
- addedDecimalSeparator = true;
- // Record field information for caller.
- fFieldStart = result.length();
- }
- result.append((i < digitList.count) ?
- (char)(digitList.digits[i] + zeroDelta) :
- zero);
- }
- // Record field information
- if (iFieldEnd == -1) {
- iFieldEnd = result.length();
- }
- delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
- iFieldStart, iFieldEnd, result);
- if (addedDecimalSeparator) {
- delegate.formatted(Field.DECIMAL_SEPARATOR,
- Field.DECIMAL_SEPARATOR,
- iFieldEnd, fFieldStart, result);
- }
- if (fFieldStart == -1) {
- fFieldStart = result.length();
- }
- delegate.formatted(FRACTION_FIELD, Field.FRACTION, Field.FRACTION,
- fFieldStart, result.length(), result);
- // The exponent is output using the pattern-specified minimum
- // exponent digits. There is no maximum limit to the exponent
- // digits, since truncating the exponent would result in an
- // unacceptable inaccuracy.
- fieldStart = result.length();
- result.append(symbols.getExponentialSymbol());
- delegate.formatted(Field.EXPONENT_SYMBOL, Field.EXPONENT_SYMBOL,
- fieldStart, result.length(), result);
- // For zero values, we force the exponent to zero. We
- // must do this here, and not earlier, because the value
- // is used to determine integer digit count above.
- if (digitList.isZero()) exponent = 0;
- boolean negativeExponent = exponent < 0;
- if (negativeExponent) {
- exponent = -exponent;
- append(result, negativePrefix, delegate,
- getNegativePrefixFieldPositions(), Field.EXPONENT_SIGN);
- }
- else {
- append(result, positivePrefix, delegate,
- getPositivePrefixFieldPositions(), Field.EXPONENT_SIGN);
- }
- digitList.set(exponent);
- int eFieldStart = result.length();
- for (int i=digitList.decimalAt; i<minExponentDigits; ++i) result.append(zero);
- for (int i=0; i<digitList.decimalAt; ++i)
- {
- result.append((i < digitList.count) ?
- (char)(digitList.digits[i] + zeroDelta) : zero);
- }
- delegate.formatted(Field.EXPONENT, Field.EXPONENT, eFieldStart,
- result.length(), result);
- fieldStart = result.length();
- if (negativeExponent) {
- append(result, negativeSuffix, delegate,
- getNegativeSuffixFieldPositions(), Field.EXPONENT_SIGN);
- }
- else {
- append(result, positiveSuffix, delegate,
- getPositiveSuffixFieldPositions(), Field.EXPONENT_SIGN);
- }
- }
- else
- {
- int iFieldStart = result.length();
- // Output the integer portion. Here 'count' is the total
- // number of integer digits we will display, including both
- // leading zeros required to satisfy getMinimumIntegerDigits,
- // and actual digits present in the number.
- int count = getMinimumIntegerDigits();
- int digitIndex = 0; // Index into digitList.fDigits[]
- if (digitList.decimalAt > 0 && count < digitList.decimalAt)
- count = digitList.decimalAt;
- // Handle the case where getMaximumIntegerDigits() is smaller
- // than the real number of integer digits. If this is so, we
- // output the least significant max integer digits. For example,
- // the value 1997 printed with 2 max integer digits is just "97".
- if (count > getMaximumIntegerDigits())
- {
- count = getMaximumIntegerDigits();
- digitIndex = digitList.decimalAt - count;
- }
- int sizeBeforeIntegerPart = result.length();
- for (int i=count-1; i>=0; --i)
- {
- if (i < digitList.decimalAt && digitIndex < digitList.count)
- {
- // Output a real digit
- result.append((char)(digitList.digits[digitIndex++] + zeroDelta));
- }
- else
- {
- // Output a leading zero
- result.append(zero);
- }
- // Output grouping separator if necessary. Don't output a
- // grouping separator if i==0 though; that's at the end of
- // the integer part.
- if (isGroupingUsed() && i>0 && (groupingSize != 0) && (i % groupingSize == 0))
- {
- int gStart = result.length();
- result.append(grouping);
- delegate.formatted(Field.GROUPING_SEPARATOR,
- Field.GROUPING_SEPARATOR, gStart,
- result.length(), result);
- }
- }
- // Determine whether or not there are any printable fractional
- // digits. If we've used up the digits we know there aren't.
- boolean fractionPresent = (getMinimumFractionDigits() > 0) ||
- (!isInteger && digitIndex < digitList.count);
- // If there is no fraction present, and we haven't printed any
- // integer digits, then print a zero. Otherwise we won't print
- // _any_ digits, and we won't be able to parse this string.
- if (!fractionPresent && result.length() == sizeBeforeIntegerPart) {
- result.append(zero);
- }
- delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
- iFieldStart, result.length(), result);
- // Output the decimal separator if we always do so.
- int sStart = result.length();
- if (decimalSeparatorAlwaysShown || fractionPresent)
- result.append(decimal);
- if (sStart != result.length()) {
- delegate.formatted(Field.DECIMAL_SEPARATOR,
- Field.DECIMAL_SEPARATOR,
- sStart, result.length(), result);
- }
- int fFieldStart = result.length();
- for (int i=0; i < getMaximumFractionDigits(); ++i)
- {
- // Here is where we escape from the loop. We escape if we've output
- // the maximum fraction digits (specified in the for expression above).
- // We also stop when we've output the minimum digits and either:
- // we have an integer, so there is no fractional stuff to display,
- // or we're out of significant digits.
- if (i >= getMinimumFractionDigits() &&
- (isInteger || digitIndex >= digitList.count))
- break;
- // Output leading fractional zeros. These are zeros that come after
- // the decimal but before any significant digits. These are only
- // output if abs(number being formatted) < 1.0.
- if (-1-i > (digitList.decimalAt-1))
- {
- result.append(zero);
- continue;
- }
- // Output a digit, if we have any precision left, or a
- // zero if we don't. We don't want to output noise digits.
- if (!isInteger && digitIndex < digitList.count)
- {
- result.append((char)(digitList.digits[digitIndex++] + zeroDelta));
- }
- else
- {
- result.append(zero);
- }
- }
- // Record field information for caller.
- delegate.formatted(FRACTION_FIELD, Field.FRACTION, Field.FRACTION,
- fFieldStart, result.length(), result);
- }
- if (isNegative) {
- append(result, negativeSuffix, delegate,
- getNegativeSuffixFieldPositions(), Field.SIGN);
- }
- else {
- append(result, positiveSuffix, delegate,
- getPositiveSuffixFieldPositions(), Field.SIGN);
- }
- return result;
- }
- /**
- * Appends the String <code>string</code> to <code>result</code>.
- * <code>delegate</code> is notified of all the
- * <code>FieldPosition</code>s in <code>positions</code>.
- * <p>
- * If one of the <code>FieldPosition</code>s in <code>positions</code>
- * identifies a <code>SIGN</code> attribute, it is mapped to
- * <code>signAttribute</code>. This is used
- * to map the <code>SIGN</code> attribute to the <code>EXPONENT</code>
- * attribute as necessary.
- * <p>
- * This is used by <code>subformat</code> to add the prefix/suffix.
- */
- private void append(StringBuffer result, String string,
- FieldDelegate delegate,
- FieldPosition[] positions,
- Format.Field signAttribute) {
- int start = result.length();
- if (string.length() > 0) {
- result.append(string);
- for (int counter = 0, max = positions.length; counter < max;
- counter++) {
- FieldPosition fp = positions[counter];
- Format.Field attribute = fp.getFieldAttribute();
- if (attribute == Field.SIGN) {
- attribute = signAttribute;
- }
- delegate.formatted(attribute, attribute,
- start + fp.getBeginIndex(),
- start + fp.getEndIndex(), result);
- }
- }
- }
- /**
- * Parses text from a string to produce a <code>Number</code>.
- * <p>
- * The method attempts to parse text starting at the index given by
- * <code>pos</code>.
- * If parsing succeeds, then the index of <code>pos</code> is updated
- * to the index after the last character used (parsing does not necessarily
- * use all characters up to the end of the string), and the parsed
- * number is returned. The updated <code>pos</code> can be used to
- * indicate the starting point for the next call to this method.
- * If an error occurs, then the index of <code>pos</code> is not
- * changed, the error index of <code>pos</code> is set to the index of
- * the character where the error occurred, and null is returned.
- * <p>
- * The most economical subclass that can represent the number given by the
- * string is chosen. Most integer values are returned as <code>Long</code>
- * objects, no matter how they are written: <code>"17"</code> and
- * <code>"17.000"</code> both parse to <code>Long(17)</code>. Values that
- * cannot fit into a <code>Long</code> are returned as
- * <code>Double</code>s. This includes values with a fractional part,
- * infinite values, <code>NaN</code>, and the value -0.0.
- * <code>DecimalFormat</code> does <em>not</em> decide whether to return
- * a <code>Double</code> or a <code>Long</code> based on the presence of a
- * decimal separator in the source string. Doing so would prevent integers
- * that overflow the mantissa of a double, such as
- * <code>"10,000,000,000,000,000.00"</code>, from being parsed accurately.
- * Currently, the only classes that <code>parse</code> returns are
- * <code>Long</code> and <code>Double</code>, but callers should not rely
- * on this. Callers may use the <code>Number</code> methods
- * <code>doubleValue</code>, <code>longValue</code>, etc., to obtain the
- * type they want.
- * <p>
- * <code>DecimalFormat</code> parses all Unicode characters that represent
- * decimal digits, as defined by <code>Character.digit()</code>. In
- * addition, <code>DecimalFormat</code> also recognizes as digits the ten
- * consecutive characters starting with the localized zero digit defined in
- * the <code>DecimalFormatSymbols</code> object.
- *
- * @param text the string to be parsed
- * @param pos A <code>ParsePosition</code> object with index and error
- * index information as described above.
- * @return the parsed value, or <code>null</code> if the parse fails
- * @exception NullPointerException if <code>text</code> or
- * <code>pos</code> is null.
- */
- public Number parse(String text, ParsePosition pos)
- {
- // special case NaN
- if (text.regionMatches(pos.index, symbols.getNaN(),
- 0, symbols.getNaN().length())) {
- pos.index = pos.index + symbols.getNaN().length();
- return new Double(Double.NaN);
- }
- boolean[] status = new boolean[STATUS_LENGTH];
- if (!subparse(text, pos, digitList, false, status))
- return null;
- double doubleResult = 0.0;
- long longResult = 0;
- boolean gotDouble = true;
- // Finally, have DigitList parse the digits into a value.
- if (status[STATUS_INFINITE])
- {
- doubleResult = Double.POSITIVE_INFINITY;
- }
- else if (digitList.fitsIntoLong(status[STATUS_POSITIVE], isParseIntegerOnly()))
- {
- gotDouble = false;
- longResult = digitList.getLong();
- }
- else doubleResult = digitList.getDouble();
- // Divide by multiplier. We have to be careful here not to do unneeded
- // conversions between double and long.
- if (multiplier != 1)
- {
- if (gotDouble)
- doubleResult /= multiplier;
- else {
- // Avoid converting to double if we can
- if (longResult % multiplier == 0) {
- longResult /= multiplier;
- } else {
- doubleResult = ((double)longResult) / multiplier;
- if (doubleResult < 0) doubleResult = -doubleResult;
- gotDouble = true;
- }
- }
- }
- if (!status[STATUS_POSITIVE])
- {
- doubleResult = -doubleResult;
- // If longResult was Long.MIN_VALUE or a divisor of it (if
- // multiplier != 1) then don't negate it.
- if (longResult > 0) {
- longResult = -longResult;
- }
- }
- // At this point, if we divided the result by the multiplier, the result may
- // fit into a long. We check for this case and return a long if possible.
- // We must do this AFTER applying the negative (if appropriate) in order to
- // handle the case of LONG_MIN; otherwise, if we do this with a positive value
- // -LONG_MIN, the double is > 0, but the long is < 0. This is a C++-specific
- // situation. We also must retain a double in the case of -0.0, which will
- // compare as == to a long 0 cast to a double (bug 4162852).
- if (multiplier != 1 && gotDouble)
- {
- longResult = (long)doubleResult;
- gotDouble = (doubleResult != (double)longResult)
- || (doubleResult == 0.0 && !status[STATUS_POSITIVE] && !isParseIntegerOnly());
- }
- return gotDouble ? (Number)new Double(doubleResult) : (Number)new Long(longResult);
- }
- private static final int STATUS_INFINITE = 0;
- private static final int STATUS_POSITIVE = 1;
- private static final int STATUS_LENGTH = 2;
- /**
- * Parse the given text into a number. The text is parsed beginning at
- * parsePosition, until an unparseable character is seen.
- * @param text The string to parse.
- * @param parsePosition The position at which to being parsing. Upon
- * return, the first unparseable character.
- * @param digits The DigitList to set to the parsed value.
- * @param isExponent If true, parse an exponent. This means no
- * infinite values and integer only.
- * @param status Upon return contains boolean status flags indicating
- * whether the value was infinite and whether it was positive.
- */
- private final boolean subparse(String text, ParsePosition parsePosition,
- DigitList digits, boolean isExponent,
- boolean status[])
- {
- int position = parsePosition.index;
- int oldStart = parsePosition.index;
- int backup;
- // check for positivePrefix; take longest
- boolean gotPositive = text.regionMatches(position,positivePrefix,0,
- positivePrefix.length());
- boolean gotNegative = text.regionMatches(position,negativePrefix,0,
- negativePrefix.length());
- if (gotPositive && gotNegative) {
- if (positivePrefix.length() > negativePrefix.length())
- gotNegative = false;
- else if (positivePrefix.length() < negativePrefix.length())
- gotPositive = false;
- }
- if (gotPositive) {
- position += positivePrefix.length();
- } else if (gotNegative) {
- position += negativePrefix.length();
- } else {
- parsePosition.errorIndex = position;
- return false;
- }
- // process digits or Inf, find decimal position
- status[STATUS_INFINITE] = false;
- if (!isExponent && text.regionMatches(position,symbols.getInfinity(),0,
- symbols.getInfinity().length()))
- {
- position += symbols.getInfinity().length();
- status[STATUS_INFINITE] = true;
- } else {
- // We now have a string of digits, possibly with grouping symbols,
- // and decimal points. We want to process these into a DigitList.
- // We don't want to put a bunch of leading zeros into the DigitList
- // though, so we keep track of the location of the decimal point,
- // put only significant digits into the DigitList, and adjust the
- // exponent as needed.
- digits.decimalAt = digits.count = 0;
- char zero = symbols.getZeroDigit();
- char decimal = isCurrencyFormat ?
- symbols.getMonetaryDecimalSeparator() : symbols.getDecimalSeparator();
- char grouping = symbols.getGroupingSeparator();
- char exponentChar = symbols.getExponentialSymbol();
- boolean sawDecimal = false;
- boolean sawExponent = false;
- boolean sawDigit = false;
- int exponent = 0; // Set to the exponent value, if any
- // We have to track digitCount ourselves, because digits.count will
- // pin when the maximum allowable digits is reached.
- int digitCount = 0;
- backup = -1;
- for (; position < text.length(); ++position)
- {
- char ch = text.charAt(position);
- /* We recognize all digit ranges, not only the Latin digit range
- * '0'..'9'. We do so by using the Character.digit() method,
- * which converts a valid Unicode digit to the range 0..9.
- *
- * The character 'ch' may be a digit. If so, place its value
- * from 0 to 9 in 'digit'. First try using the locale digit,
- * which may or MAY NOT be a standard Unicode digit range. If
- * this fails, try using the standard Unicode digit ranges by
- * calling Character.digit(). If this also fails, digit will
- * have a value outside the range 0..9.
- */
- int digit = ch - zero;
- if (digit < 0 || digit > 9) digit = Character.digit(ch, 10);
- if (digit == 0)
- {
- // Cancel out backup setting (see grouping handler below)
- backup = -1; // Do this BEFORE continue statement below!!!
- sawDigit = true;
- // Handle leading zeros
- if (digits.count == 0)
- {
- // Ignore leading zeros in integer part of number.
- if (!sawDecimal) continue;
- // If we have seen the decimal, but no significant digits yet,
- // then we account for leading zeros by decrementing the
- // digits.decimalAt into negative values.
- --digits.decimalAt;
- }
- else
- {
- ++digitCount;
- digits.append((char)(digit + '0'));
- }
- }
- else if (digit > 0 && digit <= 9) // [sic] digit==0 handled above
- {
- sawDigit = true;
- ++digitCount;
- digits.append((char)(digit + '0'));
- // Cancel out backup setting (see grouping handler below)
- backup = -1;
- }
- else if (!isExponent && ch == decimal)
- {
- // If we're only parsing integers, or if we ALREADY saw the
- // decimal, then don't parse this one.
- if (isParseIntegerOnly() || sawDecimal) break;
- digits.decimalAt = digitCount; // Not digits.count!
- sawDecimal = true;
- }
- else if (!isExponent && ch == grouping && isGroupingUsed())
- {
- if (sawDecimal) {
- break;
- }
- // Ignore grouping characters, if we are using them, but require
- // that they be followed by a digit. Otherwise we backup and
- // reprocess them.
- backup = position;
- }
- else if (!isExponent && ch == exponentChar && !sawExponent)
- {
- // Process the exponent by recursively calling this method.
- ParsePosition pos = new ParsePosition(position + 1);
- boolean[] stat = new boolean[STATUS_LENGTH];
- DigitList exponentDigits = new DigitList();
- if (subparse(text, pos, exponentDigits, true, stat) &&
- exponentDigits.fitsIntoLong(stat[STATUS_POSITIVE], true))
- {
- position = pos.index; // Advance past the exponent
- exponent = (int)exponentDigits.getLong();
- if (!stat[STATUS_POSITIVE]) exponent = -exponent;
- sawExponent = true;
- }
- break; // Whether we fail or succeed, we exit this loop
- }
- else break;
- }
- if (backup != -1) position = backup;
- // If there was no decimal point we have an integer
- if (!sawDecimal) digits.decimalAt = digitCount; // Not digits.count!
- // Adjust for exponent, if any
- digits.decimalAt += exponent;
- // If none of the text string was recognized. For example, parse
- // "x" with pattern "#0.00" (return index and error index both 0)
- // parse "$" with pattern "$#0.00". (return index 0 and error index
- // 1).
- if (!sawDigit && digitCount == 0) {
- parsePosition.index = oldStart;
- parsePosition.errorIndex = oldStart;
- return false;
- }
- }
- // check for positiveSuffix
- if (gotPositive)
- gotPositive = text.regionMatches(position,positiveSuffix,0,
- positiveSuffix.length());
- if (gotNegative)
- gotNegative = text.regionMatches(position,negativeSuffix,0,
- negativeSuffix.length());
- // if both match, take longest
- if (gotPositive && gotNegative) {
- if (positiveSuffix.length() > negativeSuffix.length())
- gotNegative = false;
- else if (positiveSuffix.length() < negativeSuffix.length())
- gotPositive = false;
- }
- // fail if neither or both
- if (gotPositive == gotNegative) {
- parsePosition.errorIndex = position;
- return false;
- }
- parsePosition.index = position +
- (gotPositive ? positiveSuffix.length() : negativeSuffix.length()); // mark success!
- status[STATUS_POSITIVE] = gotPositive;
- if (parsePosition.index == oldStart) {
- parsePosition.errorIndex = position;
- return false;
- }
- return true;
- }
- /**
- * Returns the decimal format symbols, which is generally not changed
- * by the programmer or user.
- * @return desired DecimalFormatSymbols
- * @see java.text.DecimalFormatSymbols
- */
- public DecimalFormatSymbols getDecimalFormatSymbols() {
- try {
- // don't allow multiple references
- return (DecimalFormatSymbols) symbols.clone();
- } catch (Exception foo) {
- return null; // should never happen
- }
- }
- /**
- * Sets the decimal format symbols, which is generally not changed
- * by the programmer or user.
- * @param newSymbols desired DecimalFormatSymbols
- * @see java.text.DecimalFormatSymbols
- */
- public void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols) {
- try {
- // don't allow multiple references
- symbols = (DecimalFormatSymbols) newSymbols.clone();
- expandAffixes();
- } catch (Exception foo) {
- // should never happen
- }
- }
- /**
- * Get the positive prefix.
- * <P>Examples: +123, $123, sFr123
- */
- public String getPositivePrefix () {
- return positivePrefix;
- }
- /**
- * Set the positive prefix.
- * <P>Examples: +123, $123, sFr123
- */
- public void setPositivePrefix (String newValue) {
- positivePrefix = newValue;
- posPrefixPattern = null;
- positivePrefixFieldPositions = null;
- }
- /**
- * Returns the FieldPositions of the fields in the prefix used for
- * positive numbers. This is not used if the user has explicitly set
- * a positive prefix via <code>setPositivePrefix</code>. This is
- * lazily created.
- *
- * @return FieldPositions in positive prefix
- */
- private FieldPosition[] getPositivePrefixFieldPositions() {
- if (positivePrefixFieldPositions == null) {
- if (posPrefixPattern != null) {
- positivePrefixFieldPositions = expandAffix(posPrefixPattern);
- }
- else {
- positivePrefixFieldPositions = EmptyFieldPositionArray;
- }
- }
- return positivePrefixFieldPositions;
- }
- /**
- * Get the negative prefix.
- * <P>Examples: -123, ($123) (with negative suffix), sFr-123
- */
- public String getNegativePrefix () {
- return negativePrefix;
- }
- /**
- * Set the negative prefix.
- * <P>Examples: -123, ($123) (with negative suffix), sFr-123
- */
- public void setNegativePrefix (String newValue) {
- negativePrefix = newValue;
- negPrefixPattern = null;
- }
- /**
- * Returns the FieldPositions of the fields in the prefix used for
- * negative numbers. This is not used if the user has explicitly set
- * a negative prefix via <code>setNegativePrefix</code>. This is
- * lazily created.
- *
- * @return FieldPositions in positive prefix
- */
- private FieldPosition[] getNegativePrefixFieldPositions() {
- if (negativePrefixFieldPositions == null) {
- if (negPrefixPattern != null) {
- negativePrefixFieldPositions = expandAffix(negPrefixPattern);
- }
- else {
- negativePrefixFieldPositions = EmptyFieldPositionArray;
- }
- }
- return negativePrefixFieldPositions;
- }
- /**
- * Get the positive suffix.
- * <P>Example: 123%
- */
- public String getPositiveSuffix () {
- return positiveSuffix;
- }
- /**
- * Set the positive suffix.
- * <P>Example: 123%
- */
- public void setPositiveSuffix (String newValue) {
- positiveSuffix = newValue;
- posSuffixPattern = null;
- }
- /**
- * Returns the FieldPositions of the fields in the suffix used for
- * positive numbers. This is not used if the user has explicitly set
- * a positive suffix via <code>setPositiveSuffix</code>. This is
- * lazily created.
- *
- * @return FieldPositions in positive prefix
- */
- private FieldPosition[] getPositiveSuffixFieldPositions() {
- if (positiveSuffixFieldPositions == null) {
- if (posSuffixPattern != null) {
- positiveSuffixFieldPositions = expandAffix(posSuffixPattern);
- }
- else {
- positiveSuffixFieldPositions = EmptyFieldPositionArray;
- }
- }
- return positiveSuffixFieldPositions;
- }
- /**
- * Get the negative suffix.
- * <P>Examples: -123%, ($123) (with positive suffixes)
- */
- public String getNegativeSuffix () {
- return negativeSuffix;
- }
- /**
- * Set the positive suffix.
- * <P>Examples: 123%
- */
- public void setNegativeSuffix (String newValue) {
- negativeSuffix = newValue;
- negSuffixPattern = null;
- }
- /**
- * Returns the FieldPositions of the fields in the suffix used for
- * negative numbers. This is not used if the user has explicitly set
- * a negative suffix via <code>setNegativeSuffix</code>. This is
- * lazily created.
- *
- * @return FieldPositions in positive prefix
- */
- private FieldPosition[] getNegativeSuffixFieldPositions() {
- if (negativeSuffixFieldPositions == null) {
- if (negSuffixPattern != null) {
- negativeSuffixFieldPositions = expandAffix(negSuffixPattern);
- }
- else {
- negativeSuffixFieldPositions = EmptyFieldPositionArray;
- }
- }
- return negativeSuffixFieldPositions;
- }
- /**
- * Get the multiplier for use in percent, permill, etc.
- * For a percentage, set the suffixes to have "%" and the multiplier to be 100.
- * (For Arabic, use arabic percent symbol).
- * For a permill, set the suffixes to have "\u2031" and the multiplier to be 1000.
- * <P>Examples: with 100, 1.23 -> "123", and "123" -> 1.23
- */
- public int getMultiplier () {
- return multiplier;
- }
- /**
- * Set the multiplier for use in percent, permill, etc.
- * For a percentage, set the suffixes to have "%" and the multiplier to be 100.
- * (For Arabic, use arabic percent symbol).
- * For a permill, set the suffixes to have "\u2031" and the multiplier to be 1000.
- * <P>Examples: with 100, 1.23 -> "123", and "123" -> 1.23
- */
- public void setMultiplier (int newValue) {
- multiplier = newValue;
- }
- /**
- * Return the grouping size. Grouping size is the number of digits between
- * grouping separators in the integer portion of a number. For example,
- * in the number "123,456.78", the grouping size is 3.
- * @see #setGroupingSize
- * @see java.text.NumberFormat#isGroupingUsed
- * @see java.text.DecimalFormatSymbols#getGroupingSeparator
- */
- public int getGroupingSize () {
- return groupingSize;
- }
- /**
- * Set the grouping size. Grouping size is the number of digits between
- * grouping separators in the integer portion of a number. For example,
- * in the number "123,456.78", the grouping size is 3.
- * @see #getGroupingSize
- * @see java.text.NumberFormat#setGroupingUsed
- * @see java.text.DecimalFormatSymbols#setGroupingSeparator
- */
- public void setGroupingSize (int newValue) {
- groupingSize = (byte)newValue;
- }
- /**
- * Allows you to get the behavior of the decimal separator with integers.
- * (The decimal separator will always appear with decimals.)
- * <P>Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345