diff --git a/icu4j/main/classes/core/src/com/ibm/icu/text/CurrencyMetaInfo.java b/icu4j/main/classes/core/src/com/ibm/icu/text/CurrencyMetaInfo.java
index bbb3b48384..4dc93a181a 100644
--- a/icu4j/main/classes/core/src/com/ibm/icu/text/CurrencyMetaInfo.java
+++ b/icu4j/main/classes/core/src/com/ibm/icu/text/CurrencyMetaInfo.java
@@ -11,7 +11,10 @@ import java.util.Collections;
import java.util.Date;
import java.util.List;
-import com.ibm.icu.impl.Grego;
+import com.ibm.icu.util.Calendar;
+import com.ibm.icu.util.Currency.CurrencyUsage;
+import com.ibm.icu.util.GregorianCalendar;
+import com.ibm.icu.util.TimeZone;
/**
* Provides information about currencies that is not specific to a locale.
@@ -532,11 +535,23 @@ public class CurrencyMetaInfo {
/**
* Returns the CurrencyDigits for the currency code.
+ * This is equivalent to currencyDigits(isoCode, CurrencyUsage.STANDARD);
* @param isoCode the currency code
* @return the CurrencyDigits
* @stable ICU 4.4
*/
public CurrencyDigits currencyDigits(String isoCode) {
+ return currencyDigits(isoCode, CurrencyUsage.STANDARD);
+ }
+
+ /**
+ * Returns the CurrencyDigits for the currency code with Context Usage.
+ * @param isoCode the currency code
+ * @param currencyUsage the currency usage
+ * @return the CurrencyDigits
+ * @draft ICU 54
+ */
+ public CurrencyDigits currencyDigits(String isoCode, CurrencyUsage currencyUsage) {
return defaultDigits;
}
@@ -565,7 +580,11 @@ public class CurrencyMetaInfo {
if (date == Long.MAX_VALUE || date == Long.MIN_VALUE) {
return null;
}
- return Grego.timeToString(date);
+ GregorianCalendar gc = new GregorianCalendar();
+ gc.setTimeZone(TimeZone.getTimeZone("GMT"));
+ gc.setTimeInMillis(date);
+ return "" + gc.get(Calendar.YEAR) + '-' + (gc.get(Calendar.MONTH) + 1) + '-' +
+ gc.get(Calendar.DAY_OF_MONTH);
}
private static String debugString(Object o) {
diff --git a/icu4j/main/classes/core/src/com/ibm/icu/text/DecimalFormat.java b/icu4j/main/classes/core/src/com/ibm/icu/text/DecimalFormat.java
index fc1ff98cc1..41709d54d5 100644
--- a/icu4j/main/classes/core/src/com/ibm/icu/text/DecimalFormat.java
+++ b/icu4j/main/classes/core/src/com/ibm/icu/text/DecimalFormat.java
@@ -27,256 +27,262 @@ import com.ibm.icu.impl.Utility;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.math.BigDecimal;
import com.ibm.icu.math.MathContext;
+import com.ibm.icu.text.CurrencyMetaInfo.CurrencyDigits;
import com.ibm.icu.text.PluralRules.FixedDecimal;
import com.ibm.icu.util.Currency;
+import com.ibm.icu.util.Currency.CurrencyUsage;
import com.ibm.icu.util.CurrencyAmount;
import com.ibm.icu.util.ULocale;
import com.ibm.icu.util.ULocale.Category;
/**
* {@icuenhanced java.text.DecimalFormat}.{@icu _usage_}
- *
- * DecimalFormat
is a concrete subclass of {@link NumberFormat} 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, or Indic digits.
- * It also supports different flavors of numbers, including integers ("123"), fixed-point
- * numbers ("123.4"), scientific notation ("1.23E4"), percentages ("12%"), and currency
- * amounts ("$123.00", "USD123.00", "123.00 US dollars"). All of these flavors can be
- * easily localized.
- *
- *
To obtain a {@link NumberFormat} for a specific locale (including the default
- * locale) call one of NumberFormat
's factory methods such as {@link
- * NumberFormat#getInstance}. Do not call the DecimalFormat
constructors
- * directly, unless you know what you are doing, since the {@link NumberFormat} factory
- * methods may return subclasses other than DecimalFormat
. If you need to
- * customize the format object, do something like this:
- *
- *
+ * *+ * + *+ * + *DecimalFormat
is a concrete subclass of {@link NumberFormat} 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, or Indic digits. It also supports different flavors of numbers, including integers ("123"), + * fixed-point numbers ("123.4"), scientific notation ("1.23E4"), percentages ("12%"), and currency amounts ("$123.00", + * "USD123.00", "123.00 US dollars"). All of these flavors can be easily localized. + * + *+ * To obtain a {@link NumberFormat} for a specific locale (including the default locale) call one of + *
NumberFormat
's factory methods such as {@link NumberFormat#getInstance}. Do not call the + *DecimalFormat
constructors directly, unless you know what you are doing, since the {@link NumberFormat} + * factory methods may return subclasses other thanDecimalFormat
. If you need to customize the format + * object, do something like this: + * + *+ * + *- * - ** NumberFormat f = NumberFormat.getInstance(loc); * if (f instanceof DecimalFormat) { * ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true); - * }Example Usage - * - * Print out a number using the localized number, currency, and percent - * format for each locale. - * - *
+ * + *+ * } + *+ * + *+ * Example Usage + * + * Print out a number using the localized number, currency, and percent format for each locale. + * + *
+ * + *- * - ** Locale[] locales = NumberFormat.getAvailableLocales(); * double myNumber = -1234.56; * NumberFormat format; - * for (int j=0; j<3; ++j) { - * System.out.println("FORMAT"); - * for (int i = 0; i < locales.length; ++i) { + * for (int j = 0; j < 3; ++j) { + * System.out.println("FORMAT"); + * for (int i = 0; i < locales.length; ++i) { * if (locales[i].getCountry().length() == 0) { - * // Skip language-only locales - * continue; + * // Skip language-only locales + * continue; * } * System.out.print(locales[i].getDisplayName()); * switch (j) { * case 0: - * format = NumberFormat.getInstance(locales[i]); break; + * format = NumberFormat.getInstance(locales[i]); + * break; * case 1: - * format = NumberFormat.getCurrencyInstance(locales[i]); break; + * format = NumberFormat.getCurrencyInstance(locales[i]); + * break; * default: - * format = NumberFormat.getPercentInstance(locales[i]); break; + * format = NumberFormat.getPercentInstance(locales[i]); + * break; * } * try { * // Assume format is a DecimalFormat - * System.out.print(": " + ((DecimalFormat) format).toPattern() - * + " -> " + form.format(myNumber)); - * } catch (Exception e) {} + * System.out.print(": " + ((DecimalFormat) format).toPattern() + " -> " + form.format(myNumber)); + * } catch (Exception e) { + * } * try { - * System.out.println(" -> " + format.parse(form.format(myNumber))); - * } catch (ParseException e) {} + * System.out.println(" -> " + format.parse(form.format(myNumber))); + * } catch (ParseException e) { + * } * } - * }Another example use getInstance(style).
- * Print out a number using the localized number, currency, percent, - * scientific, integer, iso currency, and plural currency format for each locale. - * - *+ * + *- * ULocale locale = new ULocale("en_US"); + * } + *+ * + *+ * Another example use getInstance(style).
+ * Print out a number using the localized number, currency, percent, scientific, integer, iso currency, and plural + * currency format for each locale. + * + *+ * + *- * + * System.out.println(" -> " + format.parse(form.format(myNumber))); + * } catch (ParseException e) { + * } + * } + *+ * ULocale locale = new ULocale("en_US"); * double myNumber = 1234.56; - * for (int j=NumberFormat.NUMBERSTYLE; j<=NumberFormat.PLURALCURRENCYSTYLE; ++j) { + * for (int j = NumberFormat.NUMBERSTYLE; j <= NumberFormat.PLURALCURRENCYSTYLE; ++j) { * NumberFormat format = NumberFormat.getInstance(locale, j); * try { * // Assume format is a DecimalFormat - * System.out.print(": " + ((DecimalFormat) format).toPattern() - * + " -> " + form.format(myNumber)); - * } catch (Exception e) {} + * System.out.print(": " + ((DecimalFormat) format).toPattern() + " -> " + form.format(myNumber)); + * } catch (Exception e) { + * } * try { - * System.out.println(" -> " + format.parse(form.format(myNumber))); - * } catch (ParseException e) {} - * }
A DecimalFormat
consists of a pattern and a set of
- * symbols. The pattern may be set directly using {@link #applyPattern}, or
- * indirectly using other API methods which manipulate aspects of the pattern, such as the
- * minimum number of integer digits. The symbols are stored in a {@link
- * DecimalFormatSymbols} object. When using the {@link NumberFormat} factory methods, the
- * pattern and symbols are read from ICU's locale data.
- *
+ *
+ *
+ * A DecimalFormat
consists of a pattern and a set of symbols. The pattern may be set
+ * directly using {@link #applyPattern}, or indirectly using other API methods which manipulate aspects of the pattern,
+ * such as the minimum number of integer digits. The symbols are stored in a {@link DecimalFormatSymbols} object. When
+ * using the {@link NumberFormat} factory methods, the pattern and symbols are read from ICU's locale data.
+ *
*
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. For example, the '#' - * character is replaced by a localized digit. Often the replacement character is the - * same as the pattern character; in the U.S. locale, the ',' grouping character is - * replaced by ','. However, the replacement is still happening, and if the symbols are - * modified, the grouping character changes. Some special characters affect the behavior - * of the formatter by their presence; for example, if the percent character is seen, then - * the value is multiplied by 100 before being displayed. - * - *
To insert a special character in a pattern as a literal, that is, without any - * special meaning, the character must be quoted. There are some exceptions to this which - * are noted below. - * - *
The characters listed here are used in non-localized patterns. Localized patterns - * use the corresponding characters taken from this formatter's {@link - * DecimalFormatSymbols} object instead, and these characters lose their special status. - * Two exceptions are the currency sign and quote, which are not localized. - * + * + *
+ * 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. For + * example, the '#' character is replaced by a localized digit. Often the replacement character is the same as the + * pattern character; in the U.S. locale, the ',' grouping character is replaced by ','. However, the replacement is + * still happening, and if the symbols are modified, the grouping character changes. Some special characters affect the + * behavior of the formatter by their presence; for example, if the percent character is seen, then the value is + * multiplied by 100 before being displayed. + * + *
+ * To insert a special character in a pattern as a literal, that is, without any special meaning, the character must be + * quoted. There are some exceptions to this which are noted below. + * + *
+ * The characters listed here are used in non-localized patterns. Localized patterns use the corresponding characters + * taken from this formatter's {@link DecimalFormatSymbols} object instead, and these characters lose their special + * status. Two exceptions are the currency sign and quote, which are not localized. + * *
- *- *
- * Symbol - * Location - * Localized? - * Meaning - * - * 0
- *Number - * Yes - * Digit - * - * 1-9
- *Number - * Yes - * '1' through '9' indicate rounding. - * - * @
- *Number - * No - * Significant digit - * - * #
- *Number - * Yes - * Digit, zero shows as absent - * - * .
- *Number - * Yes - * Decimal separator or monetary decimal separator - * - * -
- *Number - * Yes - * Minus sign - * - * ,
- *Number - * Yes - * Grouping separator - * - * E
- *Number - * Yes - * Separates mantissa and exponent in scientific notation. - * Need not be quoted in prefix or suffix. - * - * +
- *Exponent - * Yes - * Prefix positive exponents with localized plus sign. - * Need not be quoted in prefix or suffix. - * - * ;
- *Subpattern boundary - * Yes - * Separates positive and negative subpatterns - * - * %
- *Prefix or suffix - * Yes - * Multiply by 100 and show as percentage - * - * \u2030
- *Prefix or suffix - * Yes - * Multiply by 1000 and show as per mille - * - * ¤
(\u00A4
) - *Prefix or suffix - * No - * Currency sign, replaced by currency symbol. If - * doubled, replaced by international currency symbol. - * If tripled, replaced by currency plural names, for example, - * "US dollar" or "US dollars" for America. - * If present in a pattern, the monetary decimal separator - * is used instead of the decimal separator. - * - * '
- *Prefix or suffix - * No - * Used to quote special characters in a prefix or suffix, - * for example, "'#'#"
formats 123 to - *"#123"
. To create a single quote - * itself, use two in a row:"# o''clock"
. - *- * *
- *Prefix or suffix boundary - * Yes - * Pad escape, precedes pad character + * + *
* - * - *+ * Symbol + * Location + * Localized? + * Meaning + * + * 0
+ *Number + * Yes + * Digit + * + * 1-9
+ *Number + * Yes + * '1' through '9' indicate rounding. + * + * @
+ *Number + * No + * Significant digit + * + * #
+ *Number + * Yes + * Digit, zero shows as absent + * + * .
+ *Number + * Yes + * Decimal separator or monetary decimal separator + * + * -
+ *Number + * Yes + * Minus sign + * + * ,
+ *Number + * Yes + * Grouping separator + * + * E
+ *Number + * Yes + * Separates mantissa and exponent in scientific notation. Need not be quoted in prefix or suffix. + * + * +
+ *Exponent + * Yes + * Prefix positive exponents with localized plus sign. Need not be quoted in prefix or suffix. + * + * ;
+ *Subpattern boundary + * Yes + * Separates positive and negative subpatterns + * + * %
+ *Prefix or suffix + * Yes + * Multiply by 100 and show as percentage + * + * \u2030
+ *Prefix or suffix + * Yes + * Multiply by 1000 and show as per mille + * + * ¤
(\u00A4
) + *Prefix or suffix + * No + * Currency sign, replaced by currency symbol. If doubled, replaced by international currency symbol. If tripled, + * replaced by currency plural names, for example, "US dollar" or "US dollars" for America. If present in a pattern, the + * monetary decimal separator is used instead of the decimal separator. + * + * '
+ *Prefix or suffix + * No + * Used to quote special characters in a prefix or suffix, for example, "'#'#"
formats 123 to + *"#123"
. To create a single quote itself, use two in a row:"# o''clock"
. + *+ * *
+ *Prefix or suffix boundary + * Yes + * Pad escape, precedes pad character * A
DecimalFormat
pattern contains a postive and negative subpattern, for - * example, "#,##0.00;(#,##0.00)". Each subpattern has a prefix, a numeric part, and a - * suffix. If there is no explicit negative subpattern, the negative subpattern is the - * localized minus sign prefixed to the positive subpattern. That is, "0.00" alone is - * equivalent to "0.00;-0.00". 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 ignored in the negative subpattern. That means that - * "#,##0.0#;(#)" has precisely the same result as "#,##0.0#;(#,##0.0#)". - * - *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 {@link #parse} to - * be able to distinguish positive from negative values. Another example is that the - * decimal separator and thousands separator should be distinct characters, or parsing - * will be impossible. - * - *
The grouping separator is a character that separates clusters of integer - * digits to make large numbers more legible. It commonly used for thousands, but in some - * locales it separates ten-thousands. The grouping size is the number of digits - * between the grouping separators, such as 3 for "100,000,000" or 4 for "1 0000 - * 0000". There are actually two different grouping sizes: One used for the least - * significant integer digits, the primary grouping size, and one used for all - * others, the secondary grouping size. In most locales these are the same, but - * sometimes they are different. For example, if the primary grouping interval is 3, and - * the secondary is 2, then this corresponds to the pattern "#,##,##0", and the number - * 123456789 is formatted as "12,34,56,789". If a pattern contains multiple grouping - * separators, the interval between the last one and the end of the integer defines the - * primary grouping size, and the interval between the last two defines the secondary - * grouping size. All others are ignored, so "#,##,###,####" == "###,###,####" == - * "##,#,###,####". - * - *
Illegal patterns, such as "#.#.#" or "#.###,###", will cause - *
DecimalFormat
to throw an {@link IllegalArgumentException} with a message - * that describes the problem. - * + * + *+ * A
DecimalFormat
pattern contains a postive and negative subpattern, for example, "#,##0.00;(#,##0.00)". + * Each subpattern has a prefix, a numeric part, and a suffix. If there is no explicit negative subpattern, the negative + * subpattern is the localized minus sign prefixed to the positive subpattern. That is, "0.00" alone is equivalent to + * "0.00;-0.00". 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 ignored in the negative subpattern. That means + * that "#,##0.0#;(#)" has precisely the same result as "#,##0.0#;(#,##0.0#)". + * + *+ * 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 {@link #parse} to be able to distinguish positive from negative values. + * Another example is that the decimal separator and thousands separator should be distinct characters, or parsing will + * be impossible. + * + *
+ * The grouping separator is a character that separates clusters of integer digits to make large numbers more + * legible. It commonly used for thousands, but in some locales it separates ten-thousands. The grouping size + * is the number of digits between the grouping separators, such as 3 for "100,000,000" or 4 for "1 0000 0000". There + * are actually two different grouping sizes: One used for the least significant integer digits, the + * primary grouping size, and one used for all others, the secondary grouping size. In most locales + * these are the same, but sometimes they are different. For example, if the primary grouping interval is 3, and the + * secondary is 2, then this corresponds to the pattern "#,##,##0", and the number 123456789 is formatted as + * "12,34,56,789". If a pattern contains multiple grouping separators, the interval between the last one and the end of + * the integer defines the primary grouping size, and the interval between the last two defines the secondary grouping + * size. All others are ignored, so "#,##,###,####" == "###,###,####" == "##,#,###,####". + * + *
+ * Illegal patterns, such as "#.#.#" or "#.###,###", will cause
DecimalFormat
to throw an + * {@link IllegalArgumentException} with a message that describes the problem. + * *Pattern BNF
- * + * ** pattern := subpattern (';' subpattern)? * subpattern := prefix? number exponent? suffix? @@ -297,325 +303,301 @@ import com.ibm.icu.util.ULocale.Category; * C..D any character from C up to D, inclusive * S-T characters in S, except those in T *- * The first subpattern is for positive numbers. The second (optional) - * subpattern is for negative numbers. - * - *Not indicated in the BNF syntax above: - * + * + * The first subpattern is for positive numbers. The second (optional) subpattern is for negative numbers. + * + *
+ * Not indicated in the BNF syntax above: + * *
- * - *
- * + * *- The grouping separator ',' can occur inside the integer and sigDigits - * elements, between any two pattern characters of that element, as long as the integer or - * sigDigits element is not followed by the exponent element. - * - *
- Two grouping intervals are recognized: That between the decimal point and the first - * grouping symbol, and that between the first and second grouping symbols. These - * intervals are identical in most locales, but in some locales they differ. For example, - * the pattern "#,##,###" formats the number 123456789 as - * "12,34,56,789". - * - *
- The pad specifier
padSpec
may appear before the prefix, after the - * prefix, before the suffix, after the suffix, or not at all. - * - *- In place of '0', the digits '1' through '9' may be used to indicate a rounding - * increment. - * + * + *
- The grouping separator ',' can occur inside the integer and sigDigits elements, between any two pattern + * characters of that element, as long as the integer or sigDigits element is not followed by the exponent element. + * + *
- Two grouping intervals are recognized: That between the decimal point and the first grouping symbol, and that + * between the first and second grouping symbols. These intervals are identical in most locales, but in some locales + * they differ. For example, the pattern "#,##,###" formats the number 123456789 as "12,34,56,789". + * + *
- The pad specifier
padSpec
may appear before the prefix, after the prefix, before the suffix, after + * the suffix, or not at all. + * + *- In place of '0', the digits '1' through '9' may be used to indicate a rounding increment. + * *
Parsing
- * - *
DecimalFormat
parses all Unicode characters that represent decimal - * digits, as defined by {@link UCharacter#digit}. In addition, - *DecimalFormat
also recognizes as digits the ten consecutive characters - * starting with the localized zero digit defined in the {@link DecimalFormatSymbols} - * object. During formatting, the {@link DecimalFormatSymbols}-based digits are output. - * - *During parsing, grouping separators are ignored. - * - *
For currency parsing, the formatter is able to parse every currency style formats no - * matter which style the formatter is constructed with. For example, a formatter - * instance gotten from NumberFormat.getInstance(ULocale, NumberFormat.CURRENCYSTYLE) can - * parse formats such as "USD1.00" and "3.00 US dollars". - * - *
If {@link #parse(String, ParsePosition)} fails to parse a string, it returns - *
null
and leaves the parse position unchanged. The convenience method - * {@link #parse(String)} indicates parse failure by throwing a {@link - * java.text.ParseException}. - * - *Parsing an extremely large or small absolute value (such as 1.0E10000 or 1.0E-10000) - * requires huge memory allocation for representing the parsed number. Such input may expose - * a risk of DoS attacks. To prevent huge memory allocation triggered by such inputs, - *
DecimalFormat
internally limits of maximum decimal digits to be 1000. Thus, - * an input string resulting more than 1000 digits in plain decimal representation (non-exponent) - * will be treated as either overflow (positive/negative infinite) or underflow (+0.0/-0.0). - * + * + *+ *
DecimalFormat
parses all Unicode characters that represent decimal digits, as defined by + * {@link UCharacter#digit}. In addition,DecimalFormat
also recognizes as digits the ten consecutive + * characters starting with the localized zero digit defined in the {@link DecimalFormatSymbols} object. During + * formatting, the {@link DecimalFormatSymbols}-based digits are output. + * + *+ * During parsing, grouping separators are ignored. + * + *
+ * For currency parsing, the formatter is able to parse every currency style formats no matter which style the formatter + * is constructed with. For example, a formatter instance gotten from NumberFormat.getInstance(ULocale, + * NumberFormat.CURRENCYSTYLE) can parse formats such as "USD1.00" and "3.00 US dollars". + * + *
+ * If {@link #parse(String, ParsePosition)} fails to parse a string, it returns
null
and leaves the parse + * position unchanged. The convenience method {@link #parse(String)} indicates parse failure by throwing a + * {@link java.text.ParseException}. + * + *+ * Parsing an extremely large or small absolute value (such as 1.0E10000 or 1.0E-10000) requires huge memory allocation + * for representing the parsed number. Such input may expose a risk of DoS attacks. To prevent huge memory allocation + * triggered by such inputs,
DecimalFormat
internally limits of maximum decimal digits to be 1000. Thus, an + * input string resulting more than 1000 digits in plain decimal representation (non-exponent) will be treated as either + * overflow (positive/negative infinite) or underflow (+0.0/-0.0). + * *Formatting
- * - *Formatting is guided by several parameters, all of which can be specified either - * using a pattern or using the API. The following description applies to formats that do - * not use scientific notation or significant - * digits. - * - *
- * - *
- If the number of actual integer digits exceeds the maximum integer - * digits, then only the least significant digits are shown. For example, 1997 is - * formatted as "97" if the maximum integer digits is set to 2. - * - *
- If the number of actual integer digits is less than the minimum integer - * digits, then leading zeros are added. For example, 1997 is formatted as "01997" - * if the minimum integer digits is set to 5. - * - *
- If the number of actual fraction digits exceeds the maximum fraction - * digits, then half-even rounding it performed to the maximum fraction digits. For - * example, 0.125 is formatted as "0.12" if the maximum fraction digits is 2. This - * behavior can be changed by specifying a rounding increment and a rounding mode. - * - *
- If the number of actual fraction digits is less than the minimum fraction - * digits, then trailing zeros are added. For example, 0.125 is formatted as - * "0.1250" if the mimimum fraction digits is set to 4. - * - *
- Trailing fractional zeros are not displayed if they occur j positions - * after the decimal, where j is less than the maximum fraction digits. For - * example, 0.10004 is formatted as "0.1" if the maximum fraction digits is four or less. - *
Special Values - * - *
NaN
is represented as a single character, typically - *\uFFFD
. This character is determined by the {@link - * DecimalFormatSymbols} object. This is the only value for which the prefixes and - * suffixes are not used. - * - *Infinity is represented as a single character, typically
\u221E
, - * with the positive or negative prefixes and suffixes applied. The infinity character is - * determined by the {@link DecimalFormatSymbols} object. - * - *Scientific Notation
- * - *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 103. The - * mantissa is typically in the half-open interval [1.0, 10.0) or sometimes [0.0, 1.0), - * but it need not be.
DecimalFormat
supports arbitrary mantissas. - *DecimalFormat
can be instructed to use scientific notation through the API - * or through the pattern. In a pattern, the exponent character immediately followed by - * one or more digit characters indicates scientific notation. Example: "0.###E0" formats - * the number 1234 as "1.234E3". - * + * + *+ * Formatting is guided by several parameters, all of which can be specified either using a pattern or using the API. + * The following description applies to formats that do not use scientific notation or significant digits. + * *
- * - *
- * - *- 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, not the prefix and suffix from the pattern. This allows - * patterns such as "0.###E0 m/s". To prefix positive exponents with a localized plus - * sign, specify '+' between the exponent and the digits: "0.###E+0" will produce formats - * "1E+1", "1E+0", "1E-1", etc. (In localized patterns, use the localized plus sign - * rather than '+'.) - * - *
- The minimum number of integer digits is achieved by adjusting the exponent. - * Example: 0.00123 formatted with "00.###E0" yields "12.3E-4". This only happens if - * there is no maximum number of integer digits. If there is a maximum, then the minimum - * number of integer digits is fixed at one. - * - *
- The maximum number of integer digits, if present, specifies the exponent grouping. - * The most common use of this is to generate engineering notation, in which the - * exponent is a multiple of three, e.g., "##0.###E0". The number 12345 is formatted - * using "##0.####E0" as "12.345E3". - * - *
- When using scientific notation, the formatter controls the digit counts using - * significant digits logic. The maximum number of significant digits limits the total - * number of integer and fraction digits that will be shown in the mantissa; it does not - * affect parsing. For example, 12345 formatted with "##0.##E0" is "12.3E3". See the - * section on significant digits for more details. - * - *
- The number of significant digits shown is determined as follows: If - * areSignificantDigitsUsed() returns false, then the minimum number of significant digits - * shown is one, and the maximum number of significant digits shown is the sum of the - * minimum integer and maximum fraction digits, and is unaffected by the - * maximum integer digits. If this sum is zero, then all significant digits are shown. - * If areSignificantDigitsUsed() returns true, then the significant digit counts are - * specified by getMinimumSignificantDigits() and getMaximumSignificantDigits(). In this - * case, the number of integer digits is fixed at one, and there is no exponent grouping. - * - *
- Exponential patterns may not contain grouping separators. - * + *
- If the number of actual integer digits exceeds the maximum integer + * digits, then only the least significant digits are shown. For example, 1997 is formatted as "97" if the maximum + * integer digits is set to 2. + * + *
- If the number of actual integer digits is less than the minimum integer + * digits, then leading zeros are added. For example, 1997 is formatted as "01997" if the minimum integer digits is + * set to 5. + * + *
- If the number of actual fraction digits exceeds the maximum fraction + * digits, then half-even rounding it performed to the maximum fraction digits. For example, 0.125 is formatted as + * "0.12" if the maximum fraction digits is 2. This behavior can be changed by specifying a rounding increment and a + * rounding mode. + * + *
- If the number of actual fraction digits is less than the minimum fraction + * digits, then trailing zeros are added. For example, 0.125 is formatted as "0.1250" if the mimimum fraction + * digits is set to 4. + * + *
- Trailing fractional zeros are not displayed if they occur j positions after the decimal, where + * j is less than the maximum fraction digits. For example, 0.10004 is formatted as "0.1" if the maximum + * fraction digits is four or less. *
Significant Digits
- * - *DecimalFormat
has two ways of controlling how many digits are shows: (a) - * significant digits counts, or (b) integer and fraction digit counts. Integer and - * fraction digit counts are described above. When a formatter is using significant - * digits counts, the number of integer and fraction digits is not specified directly, and - * the formatter settings for these counts are ignored. Instead, the formatter uses - * however many integer and fraction digits are required to display the specified number - * of significant digits. Examples: - * + * + *+ * Special Values + * + *
+ *
NaN
is represented as a single character, typically\uFFFD
. This character is + * determined by the {@link DecimalFormatSymbols} object. This is the only value for which the prefixes and suffixes are + * not used. + * + *+ * Infinity is represented as a single character, typically
\u221E
, with the positive or negative + * prefixes and suffixes applied. The infinity character is determined by the {@link DecimalFormatSymbols} object. + * + * + *Scientific Notation
+ * + *+ * 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 103. The mantissa is typically in the half-open interval [1.0, 10.0) or sometimes + * [0.0, 1.0), but it need not be.
DecimalFormat
supports arbitrary mantissas.DecimalFormat
+ * can be instructed to use scientific notation through the API or through the pattern. In a pattern, the exponent + * character immediately followed by one or more digit characters indicates scientific notation. Example: "0.###E0" + * formats the number 1234 as "1.234E3". + * + *+ * + *
+ * + * + *- 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, not the prefix and suffix from the + * pattern. This allows patterns such as "0.###E0 m/s". To prefix positive exponents with a localized plus sign, specify + * '+' between the exponent and the digits: "0.###E+0" will produce formats "1E+1", "1E+0", "1E-1", etc. (In localized + * patterns, use the localized plus sign rather than '+'.) + * + *
- The minimum number of integer digits is achieved by adjusting the exponent. Example: 0.00123 formatted with + * "00.###E0" yields "12.3E-4". This only happens if there is no maximum number of integer digits. If there is a + * maximum, then the minimum number of integer digits is fixed at one. + * + *
- The maximum number of integer digits, if present, specifies the exponent grouping. The most common use of this is + * to generate engineering notation, in which the exponent is a multiple of three, e.g., "##0.###E0". The + * number 12345 is formatted using "##0.####E0" as "12.345E3". + * + *
- When using scientific notation, the formatter controls the digit counts using significant digits logic. The + * maximum number of significant digits limits the total number of integer and fraction digits that will be shown in the + * mantissa; it does not affect parsing. For example, 12345 formatted with "##0.##E0" is "12.3E3". See the section on + * significant digits for more details. + * + *
- The number of significant digits shown is determined as follows: If areSignificantDigitsUsed() returns false, + * then the minimum number of significant digits shown is one, and the maximum number of significant digits shown is the + * sum of the minimum integer and maximum fraction digits, and is unaffected by the maximum integer + * digits. If this sum is zero, then all significant digits are shown. If areSignificantDigitsUsed() returns true, then + * the significant digit counts are specified by getMinimumSignificantDigits() and getMaximumSignificantDigits(). In + * this case, the number of integer digits is fixed at one, and there is no exponent grouping. + * + *
- Exponential patterns may not contain grouping separators. + * + *
Significant Digits
+ * + *DecimalFormat
has two ways of controlling how many digits are shows: (a) significant digits counts, or + * (b) integer and fraction digit counts. Integer and fraction digit counts are described above. When a formatter is + * using significant digits counts, the number of integer and fraction digits is not specified directly, and the + * formatter settings for these counts are ignored. Instead, the formatter uses however many integer and fraction digits + * are required to display the specified number of significant digits. Examples: + * **- * + * *- *
*- * Pattern - * Minimum significant digits - * Maximum significant digits - * Number - * Output of format() - * - * @@@
- *3 - * 3 - * 12345 - * 12300
- *- * @@@
- *3 - * 3 - * 0.12345 - * 0.123
- *- * @@##
- *2 - * 4 - * 3.14159 - * 3.142
- *- * @@##
- *2 - * 4 - * 1.23004 - * 1.23
+ *+ * Pattern + * Minimum significant digits + * Maximum significant digits + * Number + * Output of format() + * + * @@@
+ *3 + * 3 + * 12345 + * 12300
+ *+ * @@@
+ *3 + * 3 + * 0.12345 + * 0.123
+ *+ * @@##
+ *2 + * 4 + * 3.14159 + * 3.142
+ *+ * @@##
+ *2 + * 4 + * 1.23004 + * 1.23
*- * - *
- * + * *- Significant digit counts may be expressed using patterns that specify a minimum and - * maximum number of significant digits. These are indicated by the
'@'
and - *'#'
characters. The minimum number of significant digits is the number of - *'@'
characters. The maximum number of significant digits is the number of - *'@'
characters plus the number of'#'
characters following on - * the right. For example, the pattern"@@@"
indicates exactly 3 significant - * digits. The pattern"@##"
indicates from 1 to 3 significant digits. - * Trailing zero digits to the right of the decimal separator are suppressed after the - * minimum number of significant digits have been shown. For example, the pattern - *"@##"
formats the number 0.1203 as"0.12"
. - * - *- If a pattern uses significant digits, it may not contain a decimal separator, nor - * the
'0'
pattern character. Patterns such as"@00"
or - *"@.###"
are disallowed. - * - *- Any number of
'#'
characters may be prepended to the left of the - * leftmost'@'
character. These have no effect on the minimum and maximum - * significant digits counts, but may be used to position grouping separators. For - * example,"#,#@#"
indicates a minimum of one significant digits, a maximum - * of two significant digits, and a grouping size of three. - * - *- In order to enable significant digits formatting, use a pattern containing the - *
'@'
pattern character. Alternatively, call {@link - * #setSignificantDigitsUsed setSignificantDigitsUsed(true)}. - * - *- In order to disable significant digits formatting, use a pattern that does not - * contain the
'@'
pattern character. Alternatively, call {@link - * #setSignificantDigitsUsed setSignificantDigitsUsed(false)}. - * + * + *- Significant digit counts may be expressed using patterns that specify a minimum and maximum number of significant + * digits. These are indicated by the
'@'
and'#'
characters. The minimum number of + * significant digits is the number of'@'
characters. The maximum number of significant digits is the + * number of'@'
characters plus the number of'#'
characters following on the right. For + * example, the pattern"@@@"
indicates exactly 3 significant digits. The pattern"@##"
+ * indicates from 1 to 3 significant digits. Trailing zero digits to the right of the decimal separator are suppressed + * after the minimum number of significant digits have been shown. For example, the pattern"@##"
formats + * the number 0.1203 as"0.12"
. + * + *- If a pattern uses significant digits, it may not contain a decimal separator, nor the
'0'
pattern + * character. Patterns such as"@00"
or"@.###"
are disallowed. + * + *- Any number of
'#'
characters may be prepended to the left of the leftmost'@'
+ * character. These have no effect on the minimum and maximum significant digits counts, but may be used to position + * grouping separators. For example,"#,#@#"
indicates a minimum of one significant digits, a maximum of + * two significant digits, and a grouping size of three. + * + *- In order to enable significant digits formatting, use a pattern containing the
'@'
pattern + * character. Alternatively, call {@link #setSignificantDigitsUsed setSignificantDigitsUsed(true)}. + * + *- In order to disable significant digits formatting, use a pattern that does not contain the
'@'
+ * pattern character. Alternatively, call {@link #setSignificantDigitsUsed setSignificantDigitsUsed(false)}. + * *- The number of significant digits has no effect on parsing. - * - *
- Significant digits may be used together with exponential notation. Such patterns - * are equivalent to a normal exponential pattern with a minimum and maximum integer digit - * count of one, a minimum fraction digit count of
getMinimumSignificantDigits() - + * + *
. For example, the pattern- Significant digits may be used together with exponential notation. Such patterns are equivalent to a normal + * exponential pattern with a minimum and maximum integer digit count of one, a minimum fraction digit count of + *
getMinimumSignificantDigits() - * 1
, and a maximum fraction digit count ofgetMaximumSignificantDigits() - - * 1
. For example, the pattern"@@###E0"
is equivalent to - *"0.0###E0"
. - * - *- If signficant digits are in use, then the integer and fraction digit counts, as set - * via the API, are ignored. If significant digits are not in use, then the signficant - * digit counts, as set via the API, are ignored. - * + * 1
"@@###E0"
is equivalent to"0.0###E0"
. + * + *- If signficant digits are in use, then the integer and fraction digit counts, as set via the API, are ignored. If + * significant digits are not in use, then the signficant digit counts, as set via the API, are ignored. + * *
Padding
- * - *
DecimalFormat
supports padding the result of {@link #format} to a - * specific width. Padding may be specified either through the API or through the pattern - * syntax. In a pattern the pad escape character, followed by a single pad character, - * causes padding to be parsed and formatted. The pad escape character is '*' in - * unlocalized patterns, and can be localized using {@link - * DecimalFormatSymbols#setPadEscape}. For example,"$*x#,##0.00"
formats - * 123 to"$xx123.00"
, and 1234 to"$1,234.00"
. - * + * + *+ *
DecimalFormat
supports padding the result of {@link #format} to a specific width. Padding may be + * specified either through the API or through the pattern syntax. In a pattern the pad escape character, followed by a + * single pad character, causes padding to be parsed and formatted. The pad escape character is '*' in unlocalized + * patterns, and can be localized using {@link DecimalFormatSymbols#setPadEscape}. For example, + *"$*x#,##0.00"
formats 123 to"$xx123.00"
, and 1234 to"$1,234.00"
. + * *- * - *
- * + * *- When padding is in effect, the width of the positive subpattern, including prefix - * and suffix, determines the format width. For example, in the pattern
"* #0 + * + *
- When padding is in effect, the width of the positive subpattern, including prefix and suffix, determines the + * format width. For example, in the pattern
"* #0 * o''clock"
, the format width is 10. - * + * *- The width is counted in 16-bit code units (Java
char
s). - * - *- Some parameters which usually do not matter have meaning when padding is used, - * because the pattern width is significant with padding. In the pattern "* - * ##,##,#,##0.##", the format width is 14. The initial characters "##,##," do not affect - * the grouping size or maximum integer digits, but they do affect the format width. - * - *
- Padding may be inserted at one of four locations: before the prefix, after the - * prefix, before the suffix, or after the suffix. If padding is specified in any other - * location, {@link #applyPattern} throws an {@link IllegalArgumentException}. If there - * is no prefix, before the prefix and after the prefix are equivalent, likewise for the - * suffix. - * - *
- When specified in a pattern, the 16-bit
char
immediately following the - * pad escape is the pad character. This may be any character, including a special pattern - * character. That is, the pad escape escapes the following character. If there - * is no character after the pad escape, then the pattern is illegal. - * + * + *- Some parameters which usually do not matter have meaning when padding is used, because the pattern width is + * significant with padding. In the pattern "* ##,##,#,##0.##", the format width is 14. The initial characters "##,##," + * do not affect the grouping size or maximum integer digits, but they do affect the format width. + * + *
- Padding may be inserted at one of four locations: before the prefix, after the prefix, before the suffix, or + * after the suffix. If padding is specified in any other location, {@link #applyPattern} throws an + * {@link IllegalArgumentException}. If there is no prefix, before the prefix and after the prefix are equivalent, + * likewise for the suffix. + * + *
- When specified in a pattern, the 16-bit
char
immediately following the pad escape is the pad + * character. This may be any character, including a special pattern character. That is, the pad escape escapes + * the following character. If there is no character after the pad escape, then the pattern is illegal. + * ** Rounding - * - *
DecimalFormat
supports rounding to a specific increment. For example, - * 1230 rounded to the nearest 50 is 1250. 1.234 rounded to the nearest 0.65 is 1.3. The - * rounding increment may be specified through the API or in a pattern. To specify a - * rounding increment in a pattern, include the increment in the pattern itself. "#,#50" - * specifies a rounding increment of 50. "#,##0.05" specifies a rounding increment of - * 0.05. - * + * + *+ *
DecimalFormat
supports rounding to a specific increment. For example, 1230 rounded to the nearest 50 is + * 1250. 1.234 rounded to the nearest 0.65 is 1.3. The rounding increment may be specified through the API or in a + * pattern. To specify a rounding increment in a pattern, include the increment in the pattern itself. "#,#50" specifies + * a rounding increment of 50. "#,##0.05" specifies a rounding increment of 0.05. + * *- * - *
- * + * *- Rounding only affects the string produced by formatting. It does not affect - * parsing or change any numerical values. - * - *
- A rounding mode determines how values are rounded; see the {@link - * com.ibm.icu.math.BigDecimal} documentation for a description of the modes. Rounding - * increments specified in patterns use the default mode, {@link - * com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN}. - * - *
- Some locales use rounding in their currency formats to reflect the smallest - * currency denomination. - * - *
- In a pattern, digits '1' through '9' specify rounding, but otherwise behave - * identically to digit '0'. - * + * + *
- Rounding only affects the string produced by formatting. It does not affect parsing or change any numerical + * values. + * + *
- A rounding mode determines how values are rounded; see the {@link com.ibm.icu.math.BigDecimal} + * documentation for a description of the modes. Rounding increments specified in patterns use the default mode, + * {@link com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN}. + * + *
- Some locales use rounding in their currency formats to reflect the smallest currency denomination. + * + *
- In a pattern, digits '1' through '9' specify rounding, but otherwise behave identically to digit '0'. + * *
Synchronization
- * - *
DecimalFormat
objects are not synchronized. Multiple threads should - * not access one formatter concurrently. - * - * @see java.text.Format - * @see NumberFormat - * @author Mark Davis - * @author Alan Liu + * + *+ *
DecimalFormat
objects are not synchronized. Multiple threads should not access one formatter + * concurrently. + * + * @see java.text.Format + * @see NumberFormat + * @author Mark Davis + * @author Alan Liu * @stable ICU 2.0 */ public class DecimalFormat extends NumberFormat { /** - * Creates a DecimalFormat using the default pattern and symbols for the default - *FORMAT
locale. This is a convenient way to obtain a DecimalFormat when - * internationalization is not the main concern. - * - *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. - * + * Creates a DecimalFormat using the default pattern and symbols for the default
FORMAT
locale. This is + * a convenient way to obtain a DecimalFormat when internationalization is not the main concern. + * + *+ * 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 NumberFormat#getInstance * @see NumberFormat#getNumberInstance * @see NumberFormat#getCurrencyInstance @@ -640,16 +622,17 @@ public class DecimalFormat extends NumberFormat { } /** - * Creates a DecimalFormat from the given pattern and the symbols for the default - *
FORMAT
locale. This is a convenient way to obtain a DecimalFormat when - * internationalization is not the main concern. - * - *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. - * @throws IllegalArgumentException if the given pattern is invalid. + * Creates a DecimalFormat from the given pattern and the symbols for the default
FORMAT
locale. This + * is a convenient way to obtain a DecimalFormat when internationalization is not the main concern. + * + *+ * 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. + * @throws IllegalArgumentException + * if the given pattern is invalid. * @see NumberFormat#getInstance * @see NumberFormat#getNumberInstance * @see NumberFormat#getCurrencyInstance @@ -671,17 +654,20 @@ public class DecimalFormat extends NumberFormat { } /** - * Creates a DecimalFormat from the given pattern and symbols. Use this constructor - * when you need to completely customize the behavior of the format. - * - *
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 IllegalArgumentException if the given pattern is invalid + * Creates a DecimalFormat from the given pattern and symbols. Use this constructor when you need to completely + * customize the behavior of the format. + * + *
+ * 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 IllegalArgumentException + * if the given pattern is invalid * @see NumberFormat#getInstance * @see NumberFormat#getNumberInstance * @see NumberFormat#getCurrencyInstance @@ -706,33 +692,35 @@ public class DecimalFormat extends NumberFormat { } /** - * Creates a DecimalFormat from the given pattern, symbols, information used for - * currency plural format, and format style. Use this constructor when you need to - * completely customize the behavior of the format. - * - *
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 using the setters. - * - *
If you want to completely customize a decimal format, using your own - * DecimalFormatSymbols (such as group separators) and your own information for - * currency plural formatting (such as plural rule and currency plural patterns), you - * can use this constructor. - * - * @param pattern a non-localized pattern string - * @param symbols the set of symbols to be used - * @param infoInput the information used for currency plural format, including - * currency plural patterns and plural rules. - * @param style the decimal formatting style, it is one of the following values: - * NumberFormat.NUMBERSTYLE; NumberFormat.CURRENCYSTYLE; NumberFormat.PERCENTSTYLE; - * NumberFormat.SCIENTIFICSTYLE; NumberFormat.INTEGERSTYLE; - * NumberFormat.ISOCURRENCYSTYLE; NumberFormat.PLURALCURRENCYSTYLE; + * Creates a DecimalFormat from the given pattern, symbols, information used for currency plural format, and format + * style. Use this constructor when you need to completely customize the behavior of the format. + * + *
+ * 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 using the setters. + * + *
+ * If you want to completely customize a decimal format, using your own DecimalFormatSymbols (such as group + * separators) and your own information for currency plural formatting (such as plural rule and currency plural + * patterns), you can use this constructor. + * + * @param pattern + * a non-localized pattern string + * @param symbols + * the set of symbols to be used + * @param infoInput + * the information used for currency plural format, including currency plural patterns and plural rules. + * @param style + * the decimal formatting style, it is one of the following values: NumberFormat.NUMBERSTYLE; + * NumberFormat.CURRENCYSTYLE; NumberFormat.PERCENTSTYLE; NumberFormat.SCIENTIFICSTYLE; + * NumberFormat.INTEGERSTYLE; NumberFormat.ISOCURRENCYSTYLE; NumberFormat.PLURALCURRENCYSTYLE; * @stable ICU 4.2 */ - public DecimalFormat(String pattern, DecimalFormatSymbols symbols, CurrencyPluralInfo infoInput, - int style) { + public DecimalFormat(String pattern, DecimalFormatSymbols symbols, CurrencyPluralInfo infoInput, int style) { CurrencyPluralInfo info = infoInput; if (style == NumberFormat.PLURALCURRENCYSTYLE) { info = (CurrencyPluralInfo) infoInput.clone(); @@ -740,8 +728,7 @@ public class DecimalFormat extends NumberFormat { create(pattern, symbols, info, style); } - private void create(String pattern, DecimalFormatSymbols inputSymbols, CurrencyPluralInfo info, - int inputStyle) { + private void create(String pattern, DecimalFormatSymbols inputSymbols, CurrencyPluralInfo info, int inputStyle) { if (inputStyle != NumberFormat.PLURALCURRENCYSTYLE) { createFromPatternAndSymbols(pattern, inputSymbols); } else { @@ -750,11 +737,10 @@ public class DecimalFormat extends NumberFormat { currencyPluralInfo = info; // the pattern used in format is not fixed until formatting, in which, the // number is known and will be used to pick the right pattern based on plural - // count. Here, set the pattern as the pattern of plural count == "other". + // count. Here, set the pattern as the pattern of plural count == "other". // For most locale, the patterns are probably the same for all plural // count. If not, the right pattern need to be re-applied during format. - String currencyPluralPatternForOther = - currencyPluralInfo.getCurrencyPluralPattern("other"); + String currencyPluralPatternForOther = currencyPluralInfo.getCurrencyPluralPattern("other"); applyPatternWithoutExpandAffix(currencyPluralPatternForOther, false); setCurrencyForSymbols(); } @@ -762,8 +748,7 @@ public class DecimalFormat extends NumberFormat { } /** - * Creates a DecimalFormat for currency plural format from the given pattern, symbols, - * and style. + * Creates a DecimalFormat for currency plural format from the given pattern, symbols, and style. */ DecimalFormat(String pattern, DecimalFormatSymbols inputSymbols, int style) { CurrencyPluralInfo info = null; @@ -775,6 +760,7 @@ public class DecimalFormat extends NumberFormat { /** * {@inheritDoc} + * * @stable ICU 2.0 */ @Override @@ -806,10 +792,8 @@ public class DecimalFormat extends NumberFormat { // Apply rounding after multiplier if (roundingDouble > 0.0) { // number = roundingDouble - // * round(number / roundingDouble, roundingMode, isNegative); - return round( - number, roundingDouble, roundingDoubleReciprocal, roundingMode, - isNegative); + // * round(number / roundingDouble, roundingMode, isNegative); + return round(number, roundingDouble, roundingDoubleReciprocal, roundingMode, isNegative); } return number; } @@ -825,8 +809,7 @@ public class DecimalFormat extends NumberFormat { // [Spark/CDL] The actual method to format number. If boolean value // parseAttr == true, then attribute information will be recorded. - private StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition, - boolean parseAttr) { + private StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition, boolean parseAttr) { fieldPosition.setBeginIndex(0); fieldPosition.setEndIndex(0); @@ -841,8 +824,7 @@ public class DecimalFormat extends NumberFormat { // [Spark/CDL] Add attribute for NaN here. // result.append(symbols.getNaN()); if (parseAttr) { - addAttribute(Field.INTEGER, result.length() - symbols.getNaN().length(), - result.length()); + addAttribute(Field.INTEGER, result.length() - symbols.getNaN().length(), result.length()); } if (fieldPosition.getField() == NumberFormat.INTEGER_FIELD) { fieldPosition.setEndIndex(result.length()); @@ -872,8 +854,7 @@ public class DecimalFormat extends NumberFormat { // [Spark/CDL] Add attribute for infinity here. result.append(symbols.getInfinity()); if (parseAttr) { - addAttribute(Field.INTEGER, result.length() - symbols.getInfinity().length(), - result.length()); + addAttribute(Field.INTEGER, result.length() - symbols.getInfinity().length(), result.length()); } if (fieldPosition.getField() == NumberFormat.INTEGER_FIELD) { fieldPosition.setEndIndex(result.length()); @@ -886,9 +867,9 @@ public class DecimalFormat extends NumberFormat { addPadding(result, fieldPosition, prefixLen, suffixLen); return result; } - + int precision = precision(false); - + // This is to fix rounding for scientific notation. See ticket:10542. // This code should go away when a permanent fix is done for ticket:9931. // @@ -901,38 +882,34 @@ public class DecimalFormat extends NumberFormat { // ROUND_HALF_EVEN behavior of DigitList. For example, if number = 0.003016 and roundingMode = // ROUND_DOWN and precision = 3 then after this code executes, number = 0.00301 (3 significant digits) if (useExponentialNotation && precision > 0 && number != 0.0 && roundingMode != BigDecimal.ROUND_HALF_EVEN) { - int log10RoundingIncr = 1 - precision + (int) Math.floor(Math.log10(Math.abs(number))); - double roundingIncReciprocal = 0.0; - double roundingInc = 0.0; - if (log10RoundingIncr < 0) { - roundingIncReciprocal = - BigDecimal.ONE.movePointRight(-log10RoundingIncr).doubleValue(); - } else { - roundingInc = - BigDecimal.ONE.movePointRight(log10RoundingIncr).doubleValue(); - } - number = DecimalFormat.round(number, roundingInc, roundingIncReciprocal, roundingMode, isNegative); + int log10RoundingIncr = 1 - precision + (int) Math.floor(Math.log10(Math.abs(number))); + double roundingIncReciprocal = 0.0; + double roundingInc = 0.0; + if (log10RoundingIncr < 0) { + roundingIncReciprocal = BigDecimal.ONE.movePointRight(-log10RoundingIncr).doubleValue(); + } else { + roundingInc = BigDecimal.ONE.movePointRight(log10RoundingIncr).doubleValue(); + } + number = DecimalFormat.round(number, roundingInc, roundingIncReciprocal, roundingMode, isNegative); } // End fix for ticket:10542 // At this point we are guaranteed a nonnegative finite // number. synchronized (digitList) { - digitList.set(number, precision, !useExponentialNotation && - !areSignificantDigitsUsed()); + digitList.set(number, precision, !useExponentialNotation && !areSignificantDigitsUsed()); return subformat(number, result, fieldPosition, isNegative, false, parseAttr); } } /** - * This is a special function used by the CompactDecimalFormat subclass. - * It completes only the rounding portion of the formatting and returns - * the resulting double. CompactDecimalFormat uses the result to compute - * the plural form to use. - * - * @param number The number to format. - * @return The number rounded to the correct number of significant digits - * with negative sign stripped off. + * This is a special function used by the CompactDecimalFormat subclass. It completes only the rounding portion of + * the formatting and returns the resulting double. CompactDecimalFormat uses the result to compute the plural form + * to use. + * + * @param number + * The number to format. + * @return The number rounded to the correct number of significant digits with negative sign stripped off. * @internal * @deprecated This API is ICU internal only. */ @@ -947,7 +924,7 @@ public class DecimalFormat extends NumberFormat { } return toDigitList(number).getDouble(); } - + @Deprecated DigitList toDigitList(double number) { DigitList result = new DigitList(); @@ -956,29 +933,29 @@ public class DecimalFormat extends NumberFormat { } /** - * This is a special function used by the CompactDecimalFormat subclass - * to determine if the number to be formatted is negative. - * - * @param number The number to format. - * @return True if number is negative. - * @internal - * @deprecated This API is ICU internal only. - */ - @Deprecated - boolean isNumberNegative(double number) { - if (Double.isNaN(number)) { - return false; - } - return isNegative(multiply(number)); - } + * This is a special function used by the CompactDecimalFormat subclass to determine if the number to be formatted + * is negative. + * + * @param number + * The number to format. + * @return True if number is negative. + * @internal + * @deprecated This API is ICU internal only. + */ + @Deprecated + boolean isNumberNegative(double number) { + if (Double.isNaN(number)) { + return false; + } + return isNegative(multiply(number)); + } /** - * Round a double value to the nearest multiple of the given rounding increment, - * according to the given mode. This is equivalent to rounding value/roundingInc to - * the nearest integer, according to the given mode, and returning that integer * - * roundingInc. Note this is changed from the version in 2.4, since division of - * doubles have inaccuracies. jitterbug 1871. - * + * Round a double value to the nearest multiple of the given rounding increment, according to the given mode. This + * is equivalent to rounding value/roundingInc to the nearest integer, according to the given mode, and returning + * that integer * roundingInc. Note this is changed from the version in 2.4, since division of doubles have + * inaccuracies. jitterbug 1871. + * * @param number * the absolute value of the number to be rounded * @param roundingInc @@ -991,11 +968,10 @@ public class DecimalFormat extends NumberFormat { * true if the number to be rounded is negative * @return the absolute value of the rounded result */ - private static double round(double number, double roundingInc, double roundingIncReciprocal, - int mode, boolean isNegative) { + private static double round(double number, double roundingInc, double roundingIncReciprocal, int mode, + boolean isNegative) { - double div = roundingIncReciprocal == 0.0 ? number / roundingInc : number * - roundingIncReciprocal; + double div = roundingIncReciprocal == 0.0 ? number / roundingInc : number * roundingIncReciprocal; // do the absolute cases first @@ -1022,7 +998,7 @@ public class DecimalFormat extends NumberFormat { // Handle complex cases, where the choice depends on the closer value. // We figure out the distances to the two possible values, ceiling and floor. - // We then go for the diff that is smaller. Only if they are equal does the + // We then go for the diff that is smaller. Only if they are equal does the // mode matter. double ceil = Math.ceil(div); @@ -1034,7 +1010,7 @@ public class DecimalFormat extends NumberFormat { // using the roundingInc. I don't have access to the original author of the // code but suspect that that was to produce better result in edge cases // because of machine precision, rather than simply using the difference - // between, say, ceil and div. However, it didn't work in all cases. Am + // between, say, ceil and div. However, it didn't work in all cases. Am // trying instead using an epsilon value. switch (mode) { @@ -1076,8 +1052,7 @@ public class DecimalFormat extends NumberFormat { return format(number, result, fieldPosition, false); } - private StringBuffer format(long number, StringBuffer result, FieldPosition fieldPosition, - boolean parseAttr) { + private StringBuffer format(long number, StringBuffer result, FieldPosition fieldPosition, boolean parseAttr) { fieldPosition.setBeginIndex(0); fieldPosition.setEndIndex(0); @@ -1109,8 +1084,7 @@ public class DecimalFormat extends NumberFormat { // [Spark/CDL] Use // format_BigInteger_StringBuffer_FieldPosition_boolean instead // parseAttr is used to judge whether to synthesize attributes. - return format(BigInteger.valueOf(isNegative ? -number : number), result, - fieldPosition, parseAttr); + return format(BigInteger.valueOf(isNegative ? -number : number), result, fieldPosition, parseAttr); } } @@ -1123,17 +1097,15 @@ public class DecimalFormat extends NumberFormat { /** * Formats a BigInteger number. - * + * * @stable ICU 2.0 */ @Override - public StringBuffer format(BigInteger number, StringBuffer result, - FieldPosition fieldPosition) { + public StringBuffer format(BigInteger number, StringBuffer result, FieldPosition fieldPosition) { return format(number, result, fieldPosition, false); } - private StringBuffer format(BigInteger number, StringBuffer result, FieldPosition fieldPosition, - boolean parseAttr) { + private StringBuffer format(BigInteger number, StringBuffer result, FieldPosition fieldPosition, boolean parseAttr) { // If we are to do rounding, we need to move into the BigDecimal // domain in order to do divide/multiply correctly. if (actualRoundingIncrementICU != null) { @@ -1148,24 +1120,21 @@ public class DecimalFormat extends NumberFormat { // number. synchronized (digitList) { digitList.set(number, precision(true)); - return subformat(number.intValue(), result, fieldPosition, number.signum() < 0, true, - parseAttr); + return subformat(number.intValue(), result, fieldPosition, number.signum() < 0, true, parseAttr); } } /** * Formats a BigDecimal number. - * + * * @stable ICU 2.0 */ @Override - public StringBuffer format(java.math.BigDecimal number, StringBuffer result, - FieldPosition fieldPosition) { + public StringBuffer format(java.math.BigDecimal number, StringBuffer result, FieldPosition fieldPosition) { return format(number, result, fieldPosition, false); } - private StringBuffer format(java.math.BigDecimal number, StringBuffer result, - FieldPosition fieldPosition, + private StringBuffer format(java.math.BigDecimal number, StringBuffer result, FieldPosition fieldPosition, boolean parseAttr) { if (multiplier != 1) { number = number.multiply(java.math.BigDecimal.valueOf(multiplier)); @@ -1176,48 +1145,44 @@ public class DecimalFormat extends NumberFormat { } synchronized (digitList) { - digitList.set(number, precision(false), !useExponentialNotation && - !areSignificantDigitsUsed()); - return subformat(number.doubleValue(), result, fieldPosition, number.signum() < 0, - false, parseAttr); + digitList.set(number, precision(false), !useExponentialNotation && !areSignificantDigitsUsed()); + return subformat(number.doubleValue(), result, fieldPosition, number.signum() < 0, false, parseAttr); } } /** * Formats a BigDecimal number. - * + * * @stable ICU 2.0 */ @Override - public StringBuffer format(BigDecimal number, StringBuffer result, - FieldPosition fieldPosition) { - // This method is just a copy of the corresponding java.math.BigDecimal method - // for now. It isn't very efficient since it must create a conversion object to - // do math on the rounding increment. In the future we may try to clean this up, - // or even better, limit our support to just one flavor of BigDecimal. + public StringBuffer format(BigDecimal number, StringBuffer result, FieldPosition fieldPosition) { + // This method is just a copy of the corresponding java.math.BigDecimal method + // for now. It isn't very efficient since it must create a conversion object to + // do math on the rounding increment. In the future we may try to clean this up, + // or even better, limit our support to just one flavor of BigDecimal. if (multiplier != 1) { number = number.multiply(BigDecimal.valueOf(multiplier), mathContext); } if (actualRoundingIncrementICU != null) { - number = number.divide(actualRoundingIncrementICU, 0, roundingMode) - .multiply(actualRoundingIncrementICU, mathContext); + number = number.divide(actualRoundingIncrementICU, 0, roundingMode).multiply(actualRoundingIncrementICU, + mathContext); } synchronized (digitList) { - digitList.set(number, precision(false), !useExponentialNotation && - !areSignificantDigitsUsed()); - return subformat(number.doubleValue(), result, fieldPosition, number.signum() < 0, - false, false); + digitList.set(number, precision(false), !useExponentialNotation && !areSignificantDigitsUsed()); + return subformat(number.doubleValue(), result, fieldPosition, number.signum() < 0, false, false); } } /** - * Returns true if a grouping separator belongs at the given position, based on whether - * grouping is in use and the values of the primary and secondary grouping interval. - * - * @param pos the number of integer digits to the right of the current position. Zero - * indicates the position after the rightmost integer digit. + * Returns true if a grouping separator belongs at the given position, based on whether grouping is in use and the + * values of the primary and secondary grouping interval. + * + * @param pos + * the number of integer digits to the right of the current position. Zero indicates the position after + * the rightmost integer digit. * @return true if a grouping character belongs at the current position. */ private boolean isGroupingPosition(int pos) { @@ -1233,9 +1198,8 @@ public class DecimalFormat extends NumberFormat { } /** - * Return the number of fraction digits to display, or the total - * number of digits for significant digit formats and exponential - * formats. + * Return the number of fraction digits to display, or the total number of digits for significant digit formats and + * exponential formats. */ private int precision(boolean isIntegral) { if (areSignificantDigitsUsed()) { @@ -1247,13 +1211,12 @@ public class DecimalFormat extends NumberFormat { } } - private StringBuffer subformat(int number, StringBuffer result, FieldPosition fieldPosition, - boolean isNegative, boolean isInteger, boolean parseAttr) { + private StringBuffer subformat(int number, StringBuffer result, FieldPosition fieldPosition, boolean isNegative, + boolean isInteger, boolean parseAttr) { if (currencySignCount == CURRENCY_SIGN_COUNT_IN_PLURAL_FORMAT) { // compute the plural category from the digitList plus other settings - return subformat(currencyPluralInfo.select(getFixedDecimal(number)), - result, fieldPosition, isNegative, - isInteger, parseAttr); + return subformat(currencyPluralInfo.select(getFixedDecimal(number)), result, fieldPosition, isNegative, + isInteger, parseAttr); } else { return subformat(result, fieldPosition, isNegative, isInteger, parseAttr); } @@ -1262,11 +1225,11 @@ public class DecimalFormat extends NumberFormat { /** * This is ugly, but don't see a better way to do it without major restructuring of the code. */ - /*package*/ FixedDecimal getFixedDecimal(double number) { + /* package */FixedDecimal getFixedDecimal(double number) { // get the visible fractions and the number of fraction digits. - return getFixedDecimal(number, digitList); + return getFixedDecimal(number, digitList); } - + FixedDecimal getFixedDecimal(double number, DigitList dl) { int fractionalDigitsInDigitList = dl.count - dl.decimalAt; int v; @@ -1305,14 +1268,12 @@ public class DecimalFormat extends NumberFormat { return new FixedDecimal(number, v, f); } - private StringBuffer subformat(double number, StringBuffer result, FieldPosition fieldPosition, - boolean isNegative, + private StringBuffer subformat(double number, StringBuffer result, FieldPosition fieldPosition, boolean isNegative, boolean isInteger, boolean parseAttr) { if (currencySignCount == CURRENCY_SIGN_COUNT_IN_PLURAL_FORMAT) { // compute the plural category from the digitList plus other settings - return subformat(currencyPluralInfo.select(getFixedDecimal(number)), - result, fieldPosition, isNegative, - isInteger, parseAttr); + return subformat(currencyPluralInfo.select(getFixedDecimal(number)), result, fieldPosition, isNegative, + isInteger, parseAttr); } else { return subformat(result, fieldPosition, isNegative, isInteger, parseAttr); } @@ -1322,10 +1283,10 @@ public class DecimalFormat extends NumberFormat { boolean isNegative, boolean isInteger, boolean parseAttr) { // There are 2 ways to activate currency plural format: by applying a pattern with // 3 currency sign directly, or by instantiate a decimal formatter using - // PLURALCURRENCYSTYLE. For both cases, the number of currency sign in the - // pattern is 3. Even if the number of currency sign in the pattern is 3, it does - // not mean we need to reset the pattern. For 1st case, we do not need to reset - // pattern. For 2nd case, we might need to reset pattern, if the default pattern + // PLURALCURRENCYSTYLE. For both cases, the number of currency sign in the + // pattern is 3. Even if the number of currency sign in the pattern is 3, it does + // not mean we need to reset the pattern. For 1st case, we do not need to reset + // pattern. For 2nd case, we might need to reset pattern, if the default pattern // (corresponding to plural count 'other') we use is different from the pattern // based on 'pluralCount'. // @@ -1338,10 +1299,10 @@ public class DecimalFormat extends NumberFormat { applyPatternWithoutExpandAffix(currencyPluralPattern, false); } } - // Expand the affix to the right name according to the plural rule. This is only - // used for currency plural formatting. Currency plural name is not a fixed - // static one, it is a dynamic name based on the currency plural count. So, the - // affixes need to be expanded here. For other cases, the affix is a static one + // Expand the affix to the right name according to the plural rule. This is only + // used for currency plural formatting. Currency plural name is not a fixed + // static one, it is a dynamic name based on the currency plural count. So, the + // affixes need to be expanded here. For other cases, the affix is a static one // based on pattern alone, and it is already expanded during applying pattern, or // setDecimalFormatSymbols, or setCurrency. expandAffixAdjustWidth(pluralCount); @@ -1349,11 +1310,10 @@ public class DecimalFormat extends NumberFormat { } /** - * Complete the formatting of a finite number. On entry, the - * digitList must be filled in with the correct digits. + * Complete the formatting of a finite number. On entry, the digitList must be filled in with the correct digits. */ - private StringBuffer subformat(StringBuffer result, FieldPosition fieldPosition, - boolean isNegative, boolean isInteger, boolean parseAttr) { + private StringBuffer subformat(StringBuffer result, FieldPosition fieldPosition, boolean isNegative, + boolean isInteger, boolean parseAttr) { // NOTE: This isn't required anymore because DigitList takes care of this. // // // The negative of the exponent represents the number of leading // zeros @@ -1368,11 +1328,9 @@ public class DecimalFormat extends NumberFormat { // digitList.count = 0; // } - - // 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, + // 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 @@ -1392,16 +1350,13 @@ public class DecimalFormat extends NumberFormat { return result; } - private void subformatFixed(StringBuffer result, - FieldPosition fieldPosition, - boolean isInteger, - boolean parseAttr) { - char [] digits = symbols.getDigitsLocal(); + private void subformatFixed(StringBuffer result, FieldPosition fieldPosition, boolean isInteger, boolean parseAttr) { + char[] digits = symbols.getDigitsLocal(); - char grouping = currencySignCount == CURRENCY_SIGN_COUNT_ZERO ? - symbols.getGroupingSeparator(): symbols.getMonetaryGroupingSeparator(); - char decimal = currencySignCount == CURRENCY_SIGN_COUNT_ZERO ? - symbols.getDecimalSeparator() : symbols.getMonetaryDecimalSeparator(); + char grouping = currencySignCount == CURRENCY_SIGN_COUNT_ZERO ? symbols.getGroupingSeparator() : symbols + .getMonetaryGroupingSeparator(); + char decimal = currencySignCount == CURRENCY_SIGN_COUNT_ZERO ? symbols.getDecimalSeparator() : symbols + .getMonetaryDecimalSeparator(); boolean useSigDig = areSignificantDigitsUsed(); int maxIntDig = getMaximumIntegerDigits(); int minIntDig = getMinimumIntegerDigits(); @@ -1447,8 +1402,7 @@ public class DecimalFormat extends NumberFormat { int sizeBeforeIntegerPart = result.length(); for (i = count - 1; i >= 0; --i) { - if (i < digitList.decimalAt && digitIndex < digitList.count - && sigCount < maxSigDig) { + if (i < digitList.decimalAt && digitIndex < digitList.count && sigCount < maxSigDig) { // Output a real digit result.append(digits[digitList.getDigitValue(digitIndex++)]); ++sigCount; @@ -1477,14 +1431,14 @@ public class DecimalFormat extends NumberFormat { } else if (fieldPosition.getFieldAttribute() == NumberFormat.Field.INTEGER) { fieldPosition.setEndIndex(result.length()); } - + // This handles the special case of formatting 0. For zero only, we count the // zero to the left of the decimal point as one signficant digit. Ordinarily we // do not count any leading 0's as significant. If the number we are formatting // is not zero, then either sigCount or digits.getCount() will be non-zero. if (sigCount == 0 && digitList.count == 0) { - sigCount = 1; - } + sigCount = 1; + } // Determine whether or not there are any printable fractional digits. If // we've used up the digits we know there aren't. @@ -1527,8 +1481,7 @@ public class DecimalFormat extends NumberFormat { recordFractionDigits = fieldPosition instanceof UFieldPosition; count = useSigDig ? Integer.MAX_VALUE : getMaximumFractionDigits(); - if (useSigDig && (sigCount == maxSigDig || - (sigCount >= minSigDig && digitIndex == digitList.count))) { + if (useSigDig && (sigCount == maxSigDig || (sigCount >= minSigDig && digitIndex == digitList.count))) { count = 0; } for (i = 0; i < count; ++i) { @@ -1537,8 +1490,7 @@ public class DecimalFormat extends NumberFormat { // 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 (!useSigDig && i >= getMinimumFractionDigits() && - (isInteger || digitIndex >= digitList.count)) { + if (!useSigDig && i >= getMinimumFractionDigits() && (isInteger || digitIndex >= digitList.count)) { break; } @@ -1575,8 +1527,7 @@ public class DecimalFormat extends NumberFormat { // If we reach the maximum number of significant digits, or if we output // all the real digits and reach the minimum, then we are done. ++sigCount; - if (useSigDig && (sigCount == maxSigDig || - (digitIndex == digitList.count && sigCount >= minSigDig))) { + if (useSigDig && (sigCount == maxSigDig || (digitIndex == digitList.count && sigCount >= minSigDig))) { break; } } @@ -1597,12 +1548,10 @@ public class DecimalFormat extends NumberFormat { } } - private void subformatExponential(StringBuffer result, - FieldPosition fieldPosition, - boolean parseAttr) { - char [] digits = symbols.getDigitsLocal(); - char decimal = currencySignCount == CURRENCY_SIGN_COUNT_ZERO ? - symbols.getDecimalSeparator() : symbols.getMonetaryDecimalSeparator(); + private void subformatExponential(StringBuffer result, FieldPosition fieldPosition, boolean parseAttr) { + char[] digits = symbols.getDigitsLocal(); + char decimal = currencySignCount == CURRENCY_SIGN_COUNT_ZERO ? symbols.getDecimalSeparator() : symbols + .getMonetaryDecimalSeparator(); boolean useSigDig = areSignificantDigitsUsed(); int maxIntDig = getMaximumIntegerDigits(); int minIntDig = getMinimumIntegerDigits(); @@ -1620,7 +1569,6 @@ public class DecimalFormat extends NumberFormat { fieldPosition.setBeginIndex(-1); } - // [Spark/CDL] // the begin index of integer part // the end index of integer part @@ -1654,7 +1602,7 @@ public class DecimalFormat extends NumberFormat { // 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 defined and are larger + // digits is "12.34e-3". If maximum integer digits are defined and are larger // than minimum integer digits, then minimum integer digits are ignored. int exponent = digitList.decimalAt; @@ -1701,8 +1649,7 @@ public class DecimalFormat extends NumberFormat { if (parseAttr) { // Length of decimal separator is 1. int decimalSeparatorBegin = result.length() - 1; - addAttribute(Field.DECIMAL_SEPARATOR, decimalSeparatorBegin, - result.length()); + addAttribute(Field.DECIMAL_SEPARATOR, decimalSeparatorBegin, result.length()); fracBegin = result.length(); } // Record field information for caller. @@ -1714,7 +1661,7 @@ public class DecimalFormat extends NumberFormat { recordFractionDigits = fieldPosition instanceof UFieldPosition; } - byte digit = (i < digitList.count) ? digitList.getDigitValue(i) : (byte)0; + byte digit = (i < digitList.count) ? digitList.getDigitValue(i) : (byte) 0; result.append(digits[digit]); if (recordFractionDigits) { ++fractionalDigitsCount; @@ -1769,8 +1716,8 @@ public class DecimalFormat extends NumberFormat { result.append(symbols.getExponentSeparator()); // [Spark/CDL] For exponent symbol, add an attribute. if (parseAttr) { - addAttribute(Field.EXPONENT_SYMBOL, result.length() - - symbols.getExponentSeparator().length(), result.length()); + addAttribute(Field.EXPONENT_SYMBOL, result.length() - symbols.getExponentSeparator().length(), + result.length()); } // 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 @@ -1808,8 +1755,7 @@ public class DecimalFormat extends NumberFormat { result.append(digits[0]); } for (i = 0; i < digitList.decimalAt; ++i) { - result.append((i < digitList.count) ? digits[digitList.getDigitValue(i)] - : digits[0]); + result.append((i < digitList.count) ? digits[digitList.getDigitValue(i)] : digits[0]); } // [Spark/CDL] Add attribute for exponent part. if (parseAttr) { @@ -1817,8 +1763,7 @@ public class DecimalFormat extends NumberFormat { } } - private final void addPadding(StringBuffer result, FieldPosition fieldPosition, int prefixLen, - int suffixLen) { + private final void addPadding(StringBuffer result, FieldPosition fieldPosition, int prefixLen, int suffixLen) { if (formatWidth > 0) { int len = formatWidth - result.length(); if (len > 0) { @@ -1849,21 +1794,20 @@ public class DecimalFormat extends NumberFormat { } /** - * Parses the given string, returning a
Number
object to represent the - * parsed value.Double
objects are returned to represent non-integral - * values which cannot be stored in aBigDecimal
. These are - *NaN
, infinity, -infinity, and -0.0. If {@link #isParseBigDecimal()} is - * false (the default), all other values are returned asLong
, - *BigInteger
, orBigDecimal
values, in that order of - * preference. If {@link #isParseBigDecimal()} is true, all other values are returned - * asBigDecimal
valuse. If the parse fails, null is returned. - * - * @param text the string to be parsed - * @param parsePosition defines the position where parsing is to begin, and upon - * return, the position where parsing left off. If the position has not changed upon - * return, then parsing failed. - * @return aNumber
object with the parsed value or - *null
if the parse failed + * Parses the given string, returning aNumber
object to represent the parsed value. + *Double
objects are returned to represent non-integral values which cannot be stored in a + *BigDecimal
. These areNaN
, infinity, -infinity, and -0.0. If + * {@link #isParseBigDecimal()} is false (the default), all other values are returned asLong
, + *BigInteger
, orBigDecimal
values, in that order of preference. If + * {@link #isParseBigDecimal()} is true, all other values are returned asBigDecimal
valuse. If the + * parse fails, null is returned. + * + * @param text + * the string to be parsed + * @param parsePosition + * defines the position where parsing is to begin, and upon return, the position where parsing left off. + * If the position has not changed upon return, then parsing failed. + * @return aNumber
object with the parsed value ornull
if the parse failed * @stable ICU 2.0 */ @Override @@ -1872,16 +1816,17 @@ public class DecimalFormat extends NumberFormat { } /** - * Parses text from the given string as a CurrencyAmount. Unlike the parse() method, - * this method will attempt to parse a generic currency name, searching for a match of - * this object's locale's currency display names, or for a 3-letter ISO currency - * code. This method will fail if this format is not a currency format, that is, if it - * does not contain the currency pattern symbol (U+00A4) in its prefix or suffix. - * - * @param text the text to parse - * @param pos input-output position; on input, the position within text to match; must - * have 0 <= pos.getIndex() < text.length(); on output, the position after the last - * matched character. If the parse fails, the position in unchanged upon output. + * Parses text from the given string as a CurrencyAmount. Unlike the parse() method, this method will attempt to + * parse a generic currency name, searching for a match of this object's locale's currency display names, or for a + * 3-letter ISO currency code. This method will fail if this format is not a currency format, that is, if it does + * not contain the currency pattern symbol (U+00A4) in its prefix or suffix. + * + * @param text + * the text to parse + * @param pos + * input-output position; on input, the position within text to match; must have 0 <= pos.getIndex() < + * text.length(); on output, the position after the last matched character. If the parse fails, the + * position in unchanged upon output. * @return a CurrencyAmount, or null upon failure * @stable ICU 49 */ @@ -1893,14 +1838,15 @@ public class DecimalFormat extends NumberFormat { /** * Parses the given text as either a Number or a CurrencyAmount. - * - * @param text the string to parse - * @param parsePosition input-output position; on input, the position within text to - * match; must have 0 <= pos.getIndex() < text.length(); on output, the position after - * the last matched character. If the parse fails, the position in unchanged upon - * output. - * @param currency if non-null, a CurrencyAmount is parsed and returned; otherwise a - * Number is parsed and returned + * + * @param text + * the string to parse + * @param parsePosition + * input-output position; on input, the position within text to match; must have 0 <= pos.getIndex() < + * text.length(); on output, the position after the last matched character. If the parse fails, the + * position in unchanged upon output. + * @param currency + * if non-null, a CurrencyAmount is parsed and returned; otherwise a Number is parsed and returned * @return a Number or CurrencyAmount or null */ private Object parse(String text, ParsePosition parsePosition, Currency[] currency) { @@ -1910,15 +1856,13 @@ public class DecimalFormat extends NumberFormat { // Handle NaN as a special case: // Skip padding characters, if around prefix - if (formatWidth > 0 && - (padPosition == PAD_BEFORE_PREFIX || padPosition == PAD_AFTER_PREFIX)) { + if (formatWidth > 0 && (padPosition == PAD_BEFORE_PREFIX || padPosition == PAD_AFTER_PREFIX)) { i = skipPadding(text, i); } if (text.regionMatches(i, symbols.getNaN(), 0, symbols.getNaN().length())) { i += symbols.getNaN().length(); // Skip padding characters, if around suffix - if (formatWidth > 0 && (padPosition == PAD_BEFORE_SUFFIX || - padPosition == PAD_AFTER_SUFFIX)) { + if (formatWidth > 0 && (padPosition == PAD_BEFORE_SUFFIX || padPosition == PAD_AFTER_SUFFIX)) { i = skipPadding(text, i); } parsePosition.setIndex(i); @@ -1934,9 +1878,8 @@ public class DecimalFormat extends NumberFormat { return null; } } else { - if (!subparse(text, parsePosition, digitList, status, currency, negPrefixPattern, - negSuffixPattern, posPrefixPattern, posSuffixPattern, - false, Currency.SYMBOL_NAME)) { + if (!subparse(text, parsePosition, digitList, status, currency, negPrefixPattern, negSuffixPattern, + posPrefixPattern, posSuffixPattern, false, Currency.SYMBOL_NAME)) { parsePosition.setIndex(backup); return null; } @@ -1946,8 +1889,7 @@ public class DecimalFormat extends NumberFormat { // Handle infinity if (status[STATUS_INFINITE]) { - n = new Double(status[STATUS_POSITIVE] ? Double.POSITIVE_INFINITY : - Double.NEGATIVE_INFINITY); + n = new Double(status[STATUS_POSITIVE] ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY); } // Handle underflow @@ -2006,8 +1948,7 @@ public class DecimalFormat extends NumberFormat { return (currency != null) ? (Object) new CurrencyAmount(n, currency[0]) : (Object) n; } - private boolean parseForCurrency(String text, ParsePosition parsePosition, - Currency[] currency, boolean[] status) { + private boolean parseForCurrency(String text, ParsePosition parsePosition, Currency[] currency, boolean[] status) { int origPos = parsePosition.getIndex(); if (!isReadyForParsing) { int savedCurrencySignCount = currencySignCount; @@ -2032,13 +1973,11 @@ public class DecimalFormat extends NumberFormat { DigitList tmpDigitList = new DigitList(); boolean found; if (style == NumberFormat.PLURALCURRENCYSTYLE) { - found = subparse(text, tmpPos, tmpDigitList, tmpStatus, currency, - negPrefixPattern, negSuffixPattern, posPrefixPattern, posSuffixPattern, - true, Currency.LONG_NAME); + found = subparse(text, tmpPos, tmpDigitList, tmpStatus, currency, negPrefixPattern, negSuffixPattern, + posPrefixPattern, posSuffixPattern, true, Currency.LONG_NAME); } else { - found = subparse(text, tmpPos, tmpDigitList, tmpStatus, currency, - negPrefixPattern, negSuffixPattern, posPrefixPattern, posSuffixPattern, - true, Currency.SYMBOL_NAME); + found = subparse(text, tmpPos, tmpDigitList, tmpStatus, currency, negPrefixPattern, negSuffixPattern, + posPrefixPattern, posSuffixPattern, true, Currency.SYMBOL_NAME); } if (found) { if (tmpPos.getIndex() > maxPosIndex) { @@ -2049,16 +1988,14 @@ public class DecimalFormat extends NumberFormat { } else { maxErrorPos = tmpPos.getErrorIndex(); } - // Then, parse against affix patterns. Those are currency patterns and currency + // Then, parse against affix patterns. Those are currency patterns and currency // plural patterns defined in the locale. for (AffixForCurrency affix : affixPatternsForCurrency) { tmpStatus = new boolean[STATUS_LENGTH]; tmpPos = new ParsePosition(origPos); tmpDigitList = new DigitList(); - boolean result = subparse(text, tmpPos, tmpDigitList, tmpStatus, currency, - affix.getNegPrefix(), affix.getNegSuffix(), - affix.getPosPrefix(), affix.getPosSuffix(), - true, affix.getPatternType()); + boolean result = subparse(text, tmpPos, tmpDigitList, tmpStatus, currency, affix.getNegPrefix(), + affix.getNegSuffix(), affix.getPosPrefix(), affix.getPosSuffix(), true, affix.getPatternType()); if (result) { found = true; if (tmpPos.getIndex() > maxPosIndex) { @@ -2067,14 +2004,13 @@ public class DecimalFormat extends NumberFormat { digitList = tmpDigitList; } } else { - maxErrorPos = (tmpPos.getErrorIndex() > maxErrorPos) ? tmpPos.getErrorIndex() - : maxErrorPos; + maxErrorPos = (tmpPos.getErrorIndex() > maxErrorPos) ? tmpPos.getErrorIndex() : maxErrorPos; } } - // Finally, parse against simple affix to find the match. For example, in + // Finally, parse against simple affix to find the match. For example, in // TestMonster suite, if the to-be-parsed text is "-\u00A40,00". // complexAffixCompare will not find match, since there is no ISO code matches - // "\u00A4", and the parse stops at "\u00A4". We will just use simple affix + // "\u00A4", and the parse stops at "\u00A4". We will just use simple affix // comparison (look for exact match) to pass it. // // TODO: We should parse against simple affix first when @@ -2087,9 +2023,8 @@ public class DecimalFormat extends NumberFormat { tmpDigitList = new DigitList(); // Disable complex currency parsing and try it again. - boolean result = subparse(text, tmpPos, tmpDigitList, tmpStatus, currency, - negativePrefix, negativeSuffix, positivePrefix, positiveSuffix, - false /* disable complex currency parsing */, Currency.SYMBOL_NAME); + boolean result = subparse(text, tmpPos, tmpDigitList, tmpStatus, currency, negativePrefix, negativeSuffix, + positivePrefix, positiveSuffix, false /* disable complex currency parsing */, Currency.SYMBOL_NAME); if (result) { if (tmpPos.getIndex() > maxPosIndex) { maxPosIndex = tmpPos.getIndex(); @@ -2098,8 +2033,7 @@ public class DecimalFormat extends NumberFormat { } found = true; } else { - maxErrorPos = (tmpPos.getErrorIndex() > maxErrorPos) ? tmpPos.getErrorIndex() : - maxErrorPos; + maxErrorPos = (tmpPos.getErrorIndex() > maxErrorPos) ? tmpPos.getErrorIndex() : maxErrorPos; } if (!found) { @@ -2128,13 +2062,11 @@ public class DecimalFormat extends NumberFormat { String savedFormatPattern = formatPattern; // CURRENCYSTYLE and ISOCURRENCYSTYLE should have the same prefix and suffix, so, - // only need to save one of them. Here, chose onlyApplyPatternWithoutExpandAffix - // without saving the actualy pattern in 'pattern' data member. TODO: is it uloc? - applyPatternWithoutExpandAffix(getPattern(symbols.getULocale(), NumberFormat.CURRENCYSTYLE), - false); - AffixForCurrency affixes = new AffixForCurrency( - negPrefixPattern, negSuffixPattern, posPrefixPattern, posSuffixPattern, - Currency.SYMBOL_NAME); + // only need to save one of them. Here, chose onlyApplyPatternWithoutExpandAffix + // without saving the actualy pattern in 'pattern' data member. TODO: is it uloc? + applyPatternWithoutExpandAffix(getPattern(symbols.getULocale(), NumberFormat.CURRENCYSTYLE), false); + AffixForCurrency affixes = new AffixForCurrency(negPrefixPattern, negSuffixPattern, posPrefixPattern, + posSuffixPattern, Currency.SYMBOL_NAME); affixPatternsForCurrency.add(affixes); // add plural pattern @@ -2143,12 +2075,11 @@ public class DecimalFormat extends NumberFormat { while (iter.hasNext()) { String pluralCount = iter.next(); String currencyPattern = currencyPluralInfo.getCurrencyPluralPattern(pluralCount); - if (currencyPattern != null && - currencyUnitPatternSet.contains(currencyPattern) == false) { + if (currencyPattern != null && currencyUnitPatternSet.contains(currencyPattern) == false) { currencyUnitPatternSet.add(currencyPattern); applyPatternWithoutExpandAffix(currencyPattern, false); - affixes = new AffixForCurrency(negPrefixPattern, negSuffixPattern, posPrefixPattern, - posSuffixPattern, Currency.LONG_NAME); + affixes = new AffixForCurrency(negPrefixPattern, negSuffixPattern, posPrefixPattern, posSuffixPattern, + Currency.LONG_NAME); affixPatternsForCurrency.add(affixes); } } @@ -2168,174 +2099,111 @@ public class DecimalFormat extends NumberFormat { private static final int STATUS_LENGTH = 3; private static final UnicodeSet dotEquivalents = new UnicodeSet( - //"[.\u2024\u3002\uFE12\uFE52\uFF0E\uFF61]" - 0x002E, 0x002E, - 0x2024, 0x2024, - 0x3002, 0x3002, - 0xFE12, 0xFE12, - 0xFE52, 0xFE52, - 0xFF0E, 0xFF0E, - 0xFF61, 0xFF61).freeze(); + // "[.\u2024\u3002\uFE12\uFE52\uFF0E\uFF61]" + 0x002E, 0x002E, 0x2024, 0x2024, 0x3002, 0x3002, 0xFE12, 0xFE12, 0xFE52, 0xFE52, 0xFF0E, 0xFF0E, 0xFF61, + 0xFF61).freeze(); private static final UnicodeSet commaEquivalents = new UnicodeSet( - //"[,\u060C\u066B\u3001\uFE10\uFE11\uFE50\uFE51\uFF0C\uFF64]" - 0x002C, 0x002C, - 0x060C, 0x060C, - 0x066B, 0x066B, - 0x3001, 0x3001, - 0xFE10, 0xFE11, - 0xFE50, 0xFE51, - 0xFF0C, 0xFF0C, - 0xFF64, 0xFF64).freeze(); + // "[,\u060C\u066B\u3001\uFE10\uFE11\uFE50\uFE51\uFF0C\uFF64]" + 0x002C, 0x002C, 0x060C, 0x060C, 0x066B, 0x066B, 0x3001, 0x3001, 0xFE10, 0xFE11, 0xFE50, 0xFE51, 0xFF0C, + 0xFF0C, 0xFF64, 0xFF64).freeze(); -// private static final UnicodeSet otherGroupingSeparators = new UnicodeSet( -// //"[\\ '\u00A0\u066C\u2000-\u200A\u2018\u2019\u202F\u205F\u3000\uFF07]" -// 0x0020, 0x0020, -// 0x0027, 0x0027, -// 0x00A0, 0x00A0, -// 0x066C, 0x066C, -// 0x2000, 0x200A, -// 0x2018, 0x2019, -// 0x202F, 0x202F, -// 0x205F, 0x205F, -// 0x3000, 0x3000, -// 0xFF07, 0xFF07).freeze(); + // private static final UnicodeSet otherGroupingSeparators = new UnicodeSet( + // //"[\\ '\u00A0\u066C\u2000-\u200A\u2018\u2019\u202F\u205F\u3000\uFF07]" + // 0x0020, 0x0020, + // 0x0027, 0x0027, + // 0x00A0, 0x00A0, + // 0x066C, 0x066C, + // 0x2000, 0x200A, + // 0x2018, 0x2019, + // 0x202F, 0x202F, + // 0x205F, 0x205F, + // 0x3000, 0x3000, + // 0xFF07, 0xFF07).freeze(); private static final UnicodeSet strictDotEquivalents = new UnicodeSet( - //"[.\u2024\uFE52\uFF0E\uFF61]" - 0x002E, 0x002E, - 0x2024, 0x2024, - 0xFE52, 0xFE52, - 0xFF0E, 0xFF0E, - 0xFF61, 0xFF61).freeze(); + // "[.\u2024\uFE52\uFF0E\uFF61]" + 0x002E, 0x002E, 0x2024, 0x2024, 0xFE52, 0xFE52, 0xFF0E, 0xFF0E, 0xFF61, 0xFF61).freeze(); private static final UnicodeSet strictCommaEquivalents = new UnicodeSet( - //"[,\u066B\uFE10\uFE50\uFF0C]" - 0x002C, 0x002C, - 0x066B, 0x066B, - 0xFE10, 0xFE10, - 0xFE50, 0xFE50, - 0xFF0C, 0xFF0C).freeze(); + // "[,\u066B\uFE10\uFE50\uFF0C]" + 0x002C, 0x002C, 0x066B, 0x066B, 0xFE10, 0xFE10, 0xFE50, 0xFE50, 0xFF0C, 0xFF0C).freeze(); -// private static final UnicodeSet strictOtherGroupingSeparators = new UnicodeSet( -// //"[\\ '\u00A0\u066C\u2000-\u200A\u2018\u2019\u202F\u205F\u3000\uFF07]" -// 0x0020, 0x0020, -// 0x0027, 0x0027, -// 0x00A0, 0x00A0, -// 0x066C, 0x066C, -// 0x2000, 0x200A, -// 0x2018, 0x2019, -// 0x202F, 0x202F, -// 0x205F, 0x205F, -// 0x3000, 0x3000, -// 0xFF07, 0xFF07).freeze(); + // private static final UnicodeSet strictOtherGroupingSeparators = new UnicodeSet( + // //"[\\ '\u00A0\u066C\u2000-\u200A\u2018\u2019\u202F\u205F\u3000\uFF07]" + // 0x0020, 0x0020, + // 0x0027, 0x0027, + // 0x00A0, 0x00A0, + // 0x066C, 0x066C, + // 0x2000, 0x200A, + // 0x2018, 0x2019, + // 0x202F, 0x202F, + // 0x205F, 0x205F, + // 0x3000, 0x3000, + // 0xFF07, 0xFF07).freeze(); private static final UnicodeSet defaultGroupingSeparators = - // new UnicodeSet(dotEquivalents).addAll(commaEquivalents) - // .addAll(otherGroupingSeparators).freeze(); - new UnicodeSet( - 0x0020, 0x0020, - 0x0027, 0x0027, - 0x002C, 0x002C, - 0x002E, 0x002E, - 0x00A0, 0x00A0, - 0x060C, 0x060C, - 0x066B, 0x066C, - 0x2000, 0x200A, - 0x2018, 0x2019, - 0x2024, 0x2024, - 0x202F, 0x202F, - 0x205F, 0x205F, - 0x3000, 0x3002, - 0xFE10, 0xFE12, - 0xFE50, 0xFE52, - 0xFF07, 0xFF07, - 0xFF0C, 0xFF0C, - 0xFF0E, 0xFF0E, - 0xFF61, 0xFF61, - 0xFF64, 0xFF64).freeze(); + // new UnicodeSet(dotEquivalents).addAll(commaEquivalents) + // .addAll(otherGroupingSeparators).freeze(); + new UnicodeSet(0x0020, 0x0020, 0x0027, 0x0027, 0x002C, 0x002C, 0x002E, 0x002E, 0x00A0, 0x00A0, 0x060C, 0x060C, + 0x066B, 0x066C, 0x2000, 0x200A, 0x2018, 0x2019, 0x2024, 0x2024, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, + 0x3002, 0xFE10, 0xFE12, 0xFE50, 0xFE52, 0xFF07, 0xFF07, 0xFF0C, 0xFF0C, 0xFF0E, 0xFF0E, 0xFF61, 0xFF61, + 0xFF64, 0xFF64).freeze(); private static final UnicodeSet strictDefaultGroupingSeparators = - // new UnicodeSet(strictDotEquivalents).addAll(strictCommaEquivalents) - // .addAll(strictOtherGroupingSeparators).freeze(); - new UnicodeSet( - 0x0020, 0x0020, - 0x0027, 0x0027, - 0x002C, 0x002C, - 0x002E, 0x002E, - 0x00A0, 0x00A0, - 0x066B, 0x066C, - 0x2000, 0x200A, - 0x2018, 0x2019, - 0x2024, 0x2024, - 0x202F, 0x202F, - 0x205F, 0x205F, - 0x3000, 0x3000, - 0xFE10, 0xFE10, - 0xFE50, 0xFE50, - 0xFE52, 0xFE52, - 0xFF07, 0xFF07, - 0xFF0C, 0xFF0C, - 0xFF0E, 0xFF0E, - 0xFF61, 0xFF61).freeze(); - - static final UnicodeSet minusSigns = - new UnicodeSet( - 0x002D, 0x002D, - 0x207B, 0x207B, - 0x208B, 0x208B, - 0x2212, 0x2212, - 0x2796, 0x2796, - 0xFE63, 0xFE63, - 0xFF0D, 0xFF0D).freeze(); - - static final UnicodeSet plusSigns = - new UnicodeSet( - 0x002B, 0x002B, - 0x207A, 0x207A, - 0x208A, 0x208A, - 0x2795, 0x2795, - 0xFB29, 0xFB29, - 0xFE62, 0xFE62, - 0xFF0B, 0xFF0B).freeze(); + // new UnicodeSet(strictDotEquivalents).addAll(strictCommaEquivalents) + // .addAll(strictOtherGroupingSeparators).freeze(); + new UnicodeSet(0x0020, 0x0020, 0x0027, 0x0027, 0x002C, 0x002C, 0x002E, 0x002E, 0x00A0, 0x00A0, 0x066B, 0x066C, + 0x2000, 0x200A, 0x2018, 0x2019, 0x2024, 0x2024, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000, 0xFE10, + 0xFE10, 0xFE50, 0xFE50, 0xFE52, 0xFE52, 0xFF07, 0xFF07, 0xFF0C, 0xFF0C, 0xFF0E, 0xFF0E, 0xFF61, 0xFF61) + .freeze(); - // equivalent grouping and decimal support - static final boolean skipExtendedSeparatorParsing = ICUConfig.get( - "com.ibm.icu.text.DecimalFormat.SkipExtendedSeparatorParsing", "false") - .equals("true"); + static final UnicodeSet minusSigns = new UnicodeSet(0x002D, 0x002D, 0x207B, 0x207B, 0x208B, 0x208B, 0x2212, 0x2212, + 0x2796, 0x2796, 0xFE63, 0xFE63, 0xFF0D, 0xFF0D).freeze(); + static final UnicodeSet plusSigns = new UnicodeSet(0x002B, 0x002B, 0x207A, 0x207A, 0x208A, 0x208A, 0x2795, 0x2795, + 0xFB29, 0xFB29, 0xFE62, 0xFE62, 0xFF0B, 0xFF0B).freeze(); // When parsing a number with big exponential value, it requires to transform the - // value into a string representation to construct BigInteger instance. We want to + // value into a string representation to construct BigInteger instance. We want to // set the maximum size because it can easily trigger OutOfMemoryException. // PARSE_MAX_EXPONENT is currently set to 1000 (See getParseMaxDigits()), // which is much bigger than MAX_VALUE of Double ( See the problem reported by ticket#5698 private int PARSE_MAX_EXPONENT = 1000; /** - * Parses 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 status Upon return contains boolean status flags indicating whether the - * value was infinite and whether it was positive. - * @param currency return value for parsed currency, for generic currency parsing - * mode, or null for normal parsing. In generic currency parsing mode, any currency is - * parsed, not just the currency that this formatter is set to. - * @param negPrefix negative prefix pattern - * @param negSuffix negative suffix pattern - * @param posPrefix positive prefix pattern - * @param negSuffix negative suffix pattern - * @param complexCurrencyParsing whether it is complex currency parsing or not. - * @param type type of currency to parse against, LONG_NAME only or not. + * Parses 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 status + * Upon return contains boolean status flags indicating whether the value was infinite and whether it was + * positive. + * @param currency + * return value for parsed currency, for generic currency parsing mode, or null for normal parsing. In + * generic currency parsing mode, any currency is parsed, not just the currency that this formatter is + * set to. + * @param negPrefix + * negative prefix pattern + * @param negSuffix + * negative suffix pattern + * @param posPrefix + * positive prefix pattern + * @param negSuffix + * negative suffix pattern + * @param complexCurrencyParsing + * whether it is complex currency parsing or not. + * @param type + * type of currency to parse against, LONG_NAME only or not. */ - private final boolean subparse( - String text, ParsePosition parsePosition, DigitList digits, - boolean status[], Currency currency[], String negPrefix, String negSuffix, String posPrefix, - String posSuffix, boolean parseComplexCurrency, int type) { + private final boolean subparse(String text, ParsePosition parsePosition, DigitList digits, boolean status[], + Currency currency[], String negPrefix, String negSuffix, String posPrefix, String posSuffix, + boolean parseComplexCurrency, int type) { int position = parsePosition.getIndex(); int oldStart = parsePosition.getIndex(); @@ -2371,23 +2239,22 @@ public class DecimalFormat extends NumberFormat { // process digits or Inf, find decimal position status[STATUS_INFINITE] = false; - if (text.regionMatches(position, symbols.getInfinity(), 0, - symbols.getInfinity().length())) { + if (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 + // 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 [] digitSymbols = symbols.getDigitsLocal(); - char decimal = (currencySignCount == CURRENCY_SIGN_COUNT_ZERO) ? - symbols.getDecimalSeparator() : symbols.getMonetaryDecimalSeparator(); - char grouping = (currencySignCount == CURRENCY_SIGN_COUNT_ZERO) ? - symbols.getGroupingSeparator() : symbols.getMonetaryGroupingSeparator(); + char[] digitSymbols = symbols.getDigitsLocal(); + char decimal = (currencySignCount == CURRENCY_SIGN_COUNT_ZERO) ? symbols.getDecimalSeparator() : symbols + .getMonetaryDecimalSeparator(); + char grouping = (currencySignCount == CURRENCY_SIGN_COUNT_ZERO) ? symbols.getGroupingSeparator() : symbols + .getMonetaryGroupingSeparator(); String exponentSep = symbols.getExponentSeparator(); boolean sawDecimal = false; @@ -2404,10 +2271,14 @@ public class DecimalFormat extends NumberFormat { int digitStart = position; // where did the digit start? int gs2 = groupingSize2 == 0 ? groupingSize : groupingSize2; - UnicodeSet decimalEquiv = skipExtendedSeparatorParsing ? UnicodeSet.EMPTY : - getEquivalentDecimals(decimal, strictParse); - UnicodeSet groupEquiv = skipExtendedSeparatorParsing ? UnicodeSet.EMPTY : - (strictParse ? strictDefaultGroupingSeparators : defaultGroupingSeparators); + // equivalent grouping and decimal support + boolean skipExtendedSeparatorParsing = ICUConfig.get( + "com.ibm.icu.text.DecimalFormat.SkipExtendedSeparatorParsing", "false").equals("true"); + + UnicodeSet decimalEquiv = skipExtendedSeparatorParsing ? UnicodeSet.EMPTY : getEquivalentDecimals(decimal, + strictParse); + UnicodeSet groupEquiv = skipExtendedSeparatorParsing ? UnicodeSet.EMPTY + : (strictParse ? strictDefaultGroupingSeparators : defaultGroupingSeparators); // We have to track digitCount ourselves, because digits.count will pin when // the maximum allowable digits is reached. @@ -2416,8 +2287,7 @@ public class DecimalFormat extends NumberFormat { int backup = -1; int ch; for (; position < text.length(); position += UTF16.getCharCount(ch)) { - ch = UTF16.charAt(text,position); - + ch = UTF16.charAt(text, position); // We recognize all digit ranges, not only the Latin digit range // '0'..'9'. We do so by using the UCharacter.digit() method, which @@ -2432,14 +2302,12 @@ public class DecimalFormat extends NumberFormat { if (digit < 0 || digit > 9) digit = UCharacter.digit(ch, 10); if (digit < 0 || digit > 9) { - for ( digit = 0 ; digit < 10 ; digit++) { - if ( ch == digitSymbols[digit] ) + for (digit = 0; digit < 10; digit++) { + if (ch == digitSymbols[digit]) break; } } - - if (digit == 0) { // Cancel out backup setting (see grouping handler below) if (strictParse && backup != -1) { @@ -2493,8 +2361,8 @@ public class DecimalFormat extends NumberFormat { backup = -1; } else if (ch == decimal) { if (strictParse) { - if (backup != -1 || - (lastGroup != -1 && countCodePoints(text,lastGroup,position) != groupingSize + 1)) { + if (backup != -1 + || (lastGroup != -1 && countCodePoints(text, lastGroup, position) != groupingSize + 1)) { strictFail = true; break; } @@ -2524,8 +2392,8 @@ public class DecimalFormat extends NumberFormat { sawGrouping = true; } else if (!sawDecimal && decimalEquiv.contains(ch)) { if (strictParse) { - if (backup != -1 || - (lastGroup != -1 && countCodePoints(text,lastGroup,position) != groupingSize + 1)) { + if (backup != -1 + || (lastGroup != -1 && countCodePoints(text, lastGroup, position) != groupingSize + 1)) { strictFail = true; break; } @@ -2564,7 +2432,7 @@ public class DecimalFormat extends NumberFormat { boolean negExp = false; int pos = position + exponentSep.length(); if (pos < text.length()) { - ch = UTF16.charAt(text,pos); + ch = UTF16.charAt(text, pos); if (ch == symbols.getPlusSign()) { ++pos; } else if (ch == symbols.getMinusSign()) { @@ -2576,16 +2444,16 @@ public class DecimalFormat extends NumberFormat { DigitList exponentDigits = new DigitList(); exponentDigits.count = 0; while (pos < text.length()) { - digit = UTF16.charAt(text,pos) - digitSymbols[0]; + digit = UTF16.charAt(text, pos) - digitSymbols[0]; if (digit < 0 || digit > 9) { // Can't parse "[1E0]" when pattern is "0.###E0;[0.###E0]" // Should update reassign the value of 'ch' in the code: digit // = Character.digit(ch, 10); [Richard/GCL] - digit = UCharacter.digit(UTF16.charAt(text,pos), 10); + digit = UCharacter.digit(UTF16.charAt(text, pos), 10); } if (digit >= 0 && digit <= 9) { exponentDigits.append((char) (digit + '0')); - pos += UTF16.getCharCount(UTF16.charAt(text,pos)); + pos += UTF16.getCharCount(UTF16.charAt(text, pos)); } else { break; } @@ -2600,7 +2468,7 @@ public class DecimalFormat extends NumberFormat { } } - // Quick overflow check for exponential part. Actual limit check + // Quick overflow check for exponential part. Actual limit check // will be done later in this code. if (exponentDigits.count > 10 /* maximum decimal digits for int */) { if (negExp) { @@ -2636,7 +2504,7 @@ public class DecimalFormat extends NumberFormat { // check for strict parse errors if (strictParse && !sawDecimal) { - if (lastGroup != -1 && countCodePoints(text,lastGroup,position) != groupingSize + 1) { + if (lastGroup != -1 && countCodePoints(text, lastGroup, position) != groupingSize + 1) { strictFail = true; } } @@ -2715,18 +2583,19 @@ public class DecimalFormat extends NumberFormat { } // Utility method used to count the number of codepoints - private int countCodePoints(String str,int start, int end) { + private int countCodePoints(String str, int start, int end) { int count = 0; int index = start; - while ( index < end ) { + while (index < end) { count++; index += UTF16.getCharCount(UTF16.charAt(str, index)); } return count; } + /** - * Returns a set of characters equivalent to the given desimal separator used for - * parsing number. This method may return an empty set. + * Returns a set of characters equivalent to the given desimal separator used for parsing number. This method may + * return an empty set. */ private UnicodeSet getEquivalentDecimals(char decimal, boolean strictParse) { UnicodeSet equivSet = UnicodeSet.EMPTY; @@ -2747,9 +2616,8 @@ public class DecimalFormat extends NumberFormat { } /** - * Starting at position, advance past a run of pad characters, if any. Return the - * index of the first character after position that is not a pad character. Result is - * >= position. + * Starting at position, advance past a run of pad characters, if any. Return the index of the first character after + * position that is not a pad character. Result is >= position. */ private final int skipPadding(String text, int position) { while (position < text.length() && text.charAt(position) == pad) { @@ -2759,25 +2627,31 @@ public class DecimalFormat extends NumberFormat { } /** - * Returns the length matched by the given affix, or -1 if none. Runs of white space - * in the affix, match runs of white space in the input. Pattern white space and input - * white space are determined differently; see code. - * - * @param text input text - * @param pos offset into input at which to begin matching + * Returns the length matched by the given affix, or -1 if none. Runs of white space in the affix, match runs of + * white space in the input. Pattern white space and input white space are determined differently; see code. + * + * @param text + * input text + * @param pos + * offset into input at which to begin matching * @param isNegative * @param isPrefix - * @param affixPat affix pattern used for currency affix comparison - * @param copmplexCurrencyParsing whether it is currency parsing or not - * @param type compare against currency type, LONG_NAME only or not. - * @param currency return value for parsed currency, for generic currency parsing - * mode, or null for normal parsing. In generic currency parsing mode, any currency - * is parsed, not just the currency that this formatter is set to. + * @param affixPat + * affix pattern used for currency affix comparison + * @param copmplexCurrencyParsing + * whether it is currency parsing or not + * @param type + * compare against currency type, LONG_NAME only or not. + * @param currency + * return value for parsed currency, for generic currency parsing mode, or null for normal parsing. In + * generic currency parsing mode, any currency is parsed, not just the currency that this formatter is + * set to. * @return length of input that matches, or -1 if match failure */ - private int compareAffix(String text, int pos, boolean isNegative, boolean isPrefix, - String affixPat, boolean complexCurrencyParsing, int type, Currency[] currency) { - if (currency != null || currencyChoice != null || (currencySignCount != CURRENCY_SIGN_COUNT_ZERO && complexCurrencyParsing)) { + private int compareAffix(String text, int pos, boolean isNegative, boolean isPrefix, String affixPat, + boolean complexCurrencyParsing, int type, Currency[] currency) { + if (currency != null || currencyChoice != null + || (currencySignCount != CURRENCY_SIGN_COUNT_ZERO && complexCurrencyParsing)) { return compareComplexAffix(affixPat, text, pos, type, currency); } if (isPrefix) { @@ -2792,46 +2666,48 @@ public class DecimalFormat extends NumberFormat { * Check for bidi marks: LRM, RLM, ALM */ private static boolean isBidiMark(int c) { - return (c==0x200E || c==0x200F || c==0x061C); + return (c == 0x200E || c == 0x200F || c == 0x061C); } /** * Remove bidi marks from affix */ - private static String trimMarksFromAffix(String affix) { - boolean hasBidiMark = false; - int idx = 0; - for (; idx < affix.length(); idx++) { - if (isBidiMark(affix.charAt(idx))) { - hasBidiMark = true; - break; - } - } - if (!hasBidiMark) { - return affix; - } + private static String trimMarksFromAffix(String affix) { + boolean hasBidiMark = false; + int idx = 0; + for (; idx < affix.length(); idx++) { + if (isBidiMark(affix.charAt(idx))) { + hasBidiMark = true; + break; + } + } + if (!hasBidiMark) { + return affix; + } - StringBuilder buf = new StringBuilder(); - buf.append(affix, 0, idx); - idx++; // skip the first Bidi mark - for (; idx < affix.length(); idx++) { - char c = affix.charAt(idx); - if (!isBidiMark(c)) { - buf.append(c); - } - } + StringBuilder buf = new StringBuilder(); + buf.append(affix, 0, idx); + idx++; // skip the first Bidi mark + for (; idx < affix.length(); idx++) { + char c = affix.charAt(idx); + if (!isBidiMark(c)) { + buf.append(c); + } + } - return buf.toString(); - } + return buf.toString(); + } /** - * Return the length matched by the given affix, or -1 if none. Runs of white space in - * the affix, match runs of white space in the input. Pattern white space and input - * white space are determined differently; see code. - * - * @param affix pattern string, taken as a literal - * @param input input text - * @param pos offset into input at which to begin matching + * Return the length matched by the given affix, or -1 if none. Runs of white space in the affix, match runs of + * white space in the input. Pattern white space and input white space are determined differently; see code. + * + * @param affix + * pattern string, taken as a literal + * @param input + * input text + * @param pos + * offset into input at which to begin matching * @return length of input that matches, or -1 if match failure */ private static int compareSimpleAffix(String affix, String input, int pos) { @@ -2839,7 +2715,7 @@ public class DecimalFormat extends NumberFormat { // Affixes here might consist of sign, currency symbol and related spacing, etc. // For more efficiency we should keep lazily-created trimmed affixes around in // instance variables instead of trimming each time they are used (the next step). - String trimmedAffix = (affix.length() > 1)? trimMarksFromAffix(affix): affix; + String trimmedAffix = (affix.length() > 1) ? trimMarksFromAffix(affix) : affix; for (int i = 0; i < trimmedAffix.length();) { int c = UTF16.charAt(trimmedAffix, i); int len = UTF16.getCharCount(c); @@ -2881,7 +2757,7 @@ public class DecimalFormat extends NumberFormat { return -1; } // If we skip UWhiteSpace in the input text, we need to skip it in the - // pattern. Otherwise, the previous lines may have skipped over text + // pattern. Otherwise, the previous lines may have skipped over text // (such as U+00A0) that is also in the trimmedAffix. i = skipUWhiteSpace(trimmedAffix, i); } else { @@ -2907,8 +2783,7 @@ public class DecimalFormat extends NumberFormat { } private static boolean equalWithSignCompatibility(int lhs, int rhs) { - return lhs == rhs - || (minusSigns.contains(lhs) && minusSigns.contains(rhs)) + return lhs == rhs || (minusSigns.contains(lhs) && minusSigns.contains(rhs)) || (plusSigns.contains(lhs) && plusSigns.contains(rhs)); } @@ -2940,7 +2815,7 @@ public class DecimalFormat extends NumberFormat { return pos; } - /** + /** * Skips over a run of zero or more bidi marks at pos in text. */ private static int skipBidiMarks(String text, int pos) { @@ -2954,21 +2829,24 @@ public class DecimalFormat extends NumberFormat { return pos; } - /** + /** * Returns the length matched by the given affix, or -1 if none. - * - * @param affixPat pattern string - * @param text input text - * @param pos offset into input at which to begin matching - * @param type parse against currency type, LONG_NAME only or not. - * @param currency return value for parsed currency, for generic - * currency parsing mode, or null for normal parsing. In generic - * currency parsing mode, any currency is parsed, not just the - * currency that this formatter is set to. + * + * @param affixPat + * pattern string + * @param text + * input text + * @param pos + * offset into input at which to begin matching + * @param type + * parse against currency type, LONG_NAME only or not. + * @param currency + * return value for parsed currency, for generic currency parsing mode, or null for normal parsing. In + * generic currency parsing mode, any currency is parsed, not just the currency that this formatter is + * set to. * @return position after the matched text, or -1 if match failure */ - private int compareComplexAffix(String affixPat, String text, int pos, int type, - Currency[] currency) { + private int compareComplexAffix(String affixPat, String text, int pos, int type, Currency[] currency) { int start = pos; for (int i = 0; i < affixPat.length() && pos >= 0;) { char c = affixPat.charAt(i++); @@ -3003,7 +2881,7 @@ public class DecimalFormat extends NumberFormat { // since the currency names in choice format is saved the same way as // other currency names, do not need to do currency choice parsing here. // the general currency parsing parse against all names, including names - // in choice format. assert(currency != null || (getCurrency() != null && + // in choice format. assert(currency != null || (getCurrency() != null && // currencyChoice != null)); boolean intl = i < affixPat.length() && affixPat.charAt(i) == CURRENCY_SIGN; if (intl) { @@ -3015,8 +2893,8 @@ public class DecimalFormat extends NumberFormat { intl = false; } // Parse generic currency -- anything for which we have a display name, or - // any 3-letter ISO code. Try to parse display name for our locale; first - // determine our locale. TODO: use locale in CurrencyPluralInfo + // any 3-letter ISO code. Try to parse display name for our locale; first + // determine our locale. TODO: use locale in CurrencyPluralInfo ULocale uloc = getLocale(ULocale.VALID_LOCALE); if (uloc == null) { // applyPattern has been called; use the symbols @@ -3066,9 +2944,8 @@ public class DecimalFormat extends NumberFormat { } /** - * Matches a single character at text[pos] and return the index of the next character - * upon success. Return -1 on failure. If ch is a Pattern_White_Space then match a run of - * white space in text. + * Matches a single character at text[pos] and return the index of the next character upon success. Return -1 on + * failure. If ch is a Pattern_White_Space then match a run of white space in text. */ static final int match(String text, int pos, int ch) { if (pos < 0 || pos >= text.length()) { @@ -3093,9 +2970,8 @@ public class DecimalFormat extends NumberFormat { } /** - * Matches a string at text[pos] and return the index of the next character upon - * success. Return -1 on failure. Match a run of white space in str with a run of - * white space in text. + * Matches a string at text[pos] and return the index of the next character upon success. Return -1 on failure. + * Match a run of white space in str with a run of white space in text. */ static final int match(String text, int pos, String str) { for (int i = 0; i < str.length() && pos >= 0;) { @@ -3111,7 +2987,7 @@ public class DecimalFormat extends NumberFormat { /** * Returns a copy of the decimal format symbols used by this format. - * + * * @return desired DecimalFormatSymbols * @see DecimalFormatSymbols * @stable ICU 2.0 @@ -3126,10 +3002,10 @@ public class DecimalFormat extends NumberFormat { } /** - * Sets the decimal format symbols used by this format. The format uses a copy of the - * provided symbols. - * - * @param newSymbols desired DecimalFormatSymbols + * Sets the decimal format symbols used by this format. The format uses a copy of the provided symbols. + * + * @param newSymbols + * desired DecimalFormatSymbols * @see DecimalFormatSymbols * @stable ICU 2.0 */ @@ -3140,14 +3016,13 @@ public class DecimalFormat extends NumberFormat { } /** - * Update the currency object to match the symbols. This method is used only when the - * caller has passed in a symbols object that may not be the default object for its - * locale. + * Update the currency object to match the symbols. This method is used only when the caller has passed in a symbols + * object that may not be the default object for its locale. */ private void setCurrencyForSymbols() { // Bug 4212072 Update the affix strings according to symbols in order to keep the - // affix strings up to date. [Richard/GCL] + // affix strings up to date. [Richard/GCL] // With the introduction of the Currency object, the currency symbols in the DFS // object are ignored. For backward compatibility, we check any explicitly set DFS @@ -3157,8 +3032,7 @@ public class DecimalFormat extends NumberFormat { DecimalFormatSymbols def = new DecimalFormatSymbols(symbols.getULocale()); if (symbols.getCurrencySymbol().equals(def.getCurrencySymbol()) - && symbols.getInternationalCurrencySymbol() - .equals(def.getInternationalCurrencySymbol())) { + && symbols.getInternationalCurrencySymbol().equals(def.getInternationalCurrencySymbol())) { setCurrency(Currency.getInstance(symbols.getULocale())); } else { setCurrency(null); @@ -3167,8 +3041,10 @@ public class DecimalFormat extends NumberFormat { /** * Returns the positive prefix. - * - *Examples: +123, $123, sFr123 + * + *
+ * Examples: +123, $123, sFr123 + * * @return the prefix * @stable ICU 2.0 */ @@ -3178,9 +3054,12 @@ public class DecimalFormat extends NumberFormat { /** * Sets the positive prefix. - * - *
Examples: +123, $123, sFr123 - * @param newValue the prefix + * + *
+ * Examples: +123, $123, sFr123 + * + * @param newValue + * the prefix * @stable ICU 2.0 */ public void setPositivePrefix(String newValue) { @@ -3190,9 +3069,10 @@ public class DecimalFormat extends NumberFormat { /** * Returns the negative prefix. - * - *
Examples: -123, ($123) (with negative suffix), sFr-123 - * + * + *
+ * Examples: -123, ($123) (with negative suffix), sFr-123 + * * @return the prefix * @stable ICU 2.0 */ @@ -3202,9 +3082,12 @@ public class DecimalFormat extends NumberFormat { /** * Sets the negative prefix. - * - *
Examples: -123, ($123) (with negative suffix), sFr-123 - * @param newValue the prefix + * + *
+ * Examples: -123, ($123) (with negative suffix), sFr-123 + * + * @param newValue + * the prefix * @stable ICU 2.0 */ public void setNegativePrefix(String newValue) { @@ -3214,9 +3097,10 @@ public class DecimalFormat extends NumberFormat { /** * Returns the positive suffix. - * - *
Example: 123% - * + * + *
+ * Example: 123% + * * @return the suffix * @stable ICU 2.0 */ @@ -3226,9 +3110,12 @@ public class DecimalFormat extends NumberFormat { /** * Sets the positive suffix. - * - *
Example: 123% - * @param newValue the suffix + * + *
+ * Example: 123% + * + * @param newValue + * the suffix * @stable ICU 2.0 */ public void setPositiveSuffix(String newValue) { @@ -3238,9 +3125,10 @@ public class DecimalFormat extends NumberFormat { /** * Returns the negative suffix. - * - *
Examples: -123%, ($123) (with positive suffixes) - * + * + *
+ * Examples: -123%, ($123) (with positive suffixes) + * * @return the suffix * @stable ICU 2.0 */ @@ -3250,9 +3138,12 @@ public class DecimalFormat extends NumberFormat { /** * Sets the positive suffix. - * - *
Examples: 123% - * @param newValue the suffix + * + *
+ * Examples: 123% + * + * @param newValue + * the suffix * @stable ICU 2.0 */ public void setNegativeSuffix(String newValue) { @@ -3261,13 +3152,13 @@ public class DecimalFormat extends NumberFormat { } /** - * Returns 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. - * - *
Examples: with 100, 1.23 -> "123", and "123" -> 1.23 - * + * Returns 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. + * + *
+ * Examples: with 100, 1.23 -> "123", and "123" -> 1.23 + * * @return the multiplier * @stable ICU 2.0 */ @@ -3276,14 +3167,15 @@ public class DecimalFormat extends NumberFormat { } /** - * Sets 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. - * - *
Examples: with 100, 1.23 -> "123", and "123" -> 1.23 - * - * @param newValue the multiplier + * Sets 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. + * + *
+ * Examples: with 100, 1.23 -> "123", and "123" -> 1.23 + * + * @param newValue + * the multiplier * @stable ICU 2.0 */ public void setMultiplier(int newValue) { @@ -3295,9 +3187,8 @@ public class DecimalFormat extends NumberFormat { /** * {@icu} Returns the rounding increment. - * - * @return A positive rounding increment, or
null
if a custom rounding - * increment is not in effect. + * + * @return A positive rounding increment, ornull
if a custom rounding increment is not in effect. * @see #setRoundingIncrement * @see #getRoundingMode * @see #setRoundingMode @@ -3310,12 +3201,14 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Sets the rounding increment. In the absence of a rounding increment, numbers - * will be rounded to the number of digits displayed. - * - * @param newValue A positive rounding increment, ornull
or - *BigDecimal(0.0)
to use the default rounding increment. - * @throws IllegalArgumentException ifnewValue
is < 0.0 + * {@icu} Sets the rounding increment. In the absence of a rounding increment, numbers will be rounded to the number + * of digits displayed. + * + * @param newValue + * A positive rounding increment, ornull
orBigDecimal(0.0)
to use the default + * rounding increment. + * @throws IllegalArgumentException + * ifnewValue
is < 0.0 * @see #getRoundingIncrement * @see #getRoundingMode * @see #setRoundingMode @@ -3330,12 +3223,14 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Sets the rounding increment. In the absence of a rounding increment, numbers - * will be rounded to the number of digits displayed. - * - * @param newValue A positive rounding increment, ornull
or - *BigDecimal(0.0)
to use the default rounding increment. - * @throws IllegalArgumentException ifnewValue
is < 0.0 + * {@icu} Sets the rounding increment. In the absence of a rounding increment, numbers will be rounded to the number + * of digits displayed. + * + * @param newValue + * A positive rounding increment, ornull
orBigDecimal(0.0)
to use the default + * rounding increment. + * @throws IllegalArgumentException + * ifnewValue
is < 0.0 * @see #getRoundingIncrement * @see #getRoundingMode * @see #setRoundingMode @@ -3355,12 +3250,13 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Sets the rounding increment. In the absence of a rounding increment, numbers - * will be rounded to the number of digits displayed. - * - * @param newValue A positive rounding increment, or 0.0 to use the default - * rounding increment. - * @throws IllegalArgumentException ifnewValue
is < 0.0 + * {@icu} Sets the rounding increment. In the absence of a rounding increment, numbers will be rounded to the number + * of digits displayed. + * + * @param newValue + * A positive rounding increment, or 0.0 to use the default rounding increment. + * @throws IllegalArgumentException + * ifnewValue
is < 0.0 * @see #getRoundingIncrement * @see #getRoundingMode * @see #setRoundingMode @@ -3382,9 +3278,8 @@ public class DecimalFormat extends NumberFormat { /** * Returns the rounding mode. - * - * @return A rounding mode, betweenBigDecimal.ROUND_UP
and - *BigDecimal.ROUND_UNNECESSARY
. + * + * @return A rounding mode, betweenBigDecimal.ROUND_UP
andBigDecimal.ROUND_UNNECESSARY
. * @see #setRoundingIncrement * @see #getRoundingIncrement * @see #setRoundingMode @@ -3397,12 +3292,13 @@ public class DecimalFormat extends NumberFormat { } /** - * Sets the rounding mode. This has no effect unless the rounding increment is greater - * than zero. - * - * @param roundingMode A rounding mode, betweenBigDecimal.ROUND_UP
and - *BigDecimal.ROUND_UNNECESSARY
. - * @exception IllegalArgumentException ifroundingMode
is unrecognized. + * Sets the rounding mode. This has no effect unless the rounding increment is greater than zero. + * + * @param roundingMode + * A rounding mode, betweenBigDecimal.ROUND_UP
and + *BigDecimal.ROUND_UNNECESSARY
. + * @exception IllegalArgumentException + * ifroundingMode
is unrecognized. * @see #setRoundingIncrement * @see #getRoundingIncrement * @see #getRoundingMode @@ -3420,9 +3316,9 @@ public class DecimalFormat extends NumberFormat { } /** - * Returns the width to which the output offormat()
is padded. The width is - * counted in 16-bit code units. - * + * Returns the width to which the output offormat()
is padded. The width is counted in 16-bit code + * units. + * * @return the format width, or zero if no padding is in effect * @see #setFormatWidth * @see #getPadCharacter @@ -3436,13 +3332,13 @@ public class DecimalFormat extends NumberFormat { } /** - * Sets the width to which the output offormat()
is - * padded. The width is counted in 16-bit code units. This method - * also controls whether padding is enabled. - * - * @param width the width to which to pad the result of - *format()
, or zero to disable padding - * @exception IllegalArgumentException ifwidth
is < 0 + * Sets the width to which the output offormat()
is padded. The width is counted in 16-bit code units. + * This method also controls whether padding is enabled. + * + * @param width + * the width to which to pad the result offormat()
, or zero to disable padding + * @exception IllegalArgumentException + * ifwidth
is < 0 * @see #getFormatWidth * @see #getPadCharacter * @see #setPadCharacter @@ -3459,7 +3355,7 @@ public class DecimalFormat extends NumberFormat { /** * {@icu} Returns the character used to pad to the format width. The default is ' '. - * + * * @return the pad character * @see #setFormatWidth * @see #getFormatWidth @@ -3473,10 +3369,11 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Sets the character used to pad to the format width. If padding is not - * enabled, then this will take effect if padding is later enabled. - * - * @param padChar the pad character + * {@icu} Sets the character used to pad to the format width. If padding is not enabled, then this will take effect + * if padding is later enabled. + * + * @param padChar + * the pad character * @see #setFormatWidth * @see #getFormatWidth * @see #getPadCharacter @@ -3489,13 +3386,11 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Returns the position at which padding will take place. This is the location at - * which padding will be inserted if the result offormat()
is shorter - * than the format width. - * - * @return the pad position, one ofPAD_BEFORE_PREFIX
, - *PAD_AFTER_PREFIX
,PAD_BEFORE_SUFFIX
, or - *PAD_AFTER_SUFFIX
. + * {@icu} Returns the position at which padding will take place. This is the location at which padding will be + * inserted if the result offormat()
is shorter than the format width. + * + * @return the pad position, one ofPAD_BEFORE_PREFIX
,PAD_AFTER_PREFIX
, + *PAD_BEFORE_SUFFIX
, orPAD_AFTER_SUFFIX
. * @see #setFormatWidth * @see #getFormatWidth * @see #setPadCharacter @@ -3512,14 +3407,15 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Sets the position at which padding will take place. This is the location at - * which padding will be inserted if the result offormat()
is shorter - * than the format width. This has no effect unless padding is enabled. - * - * @param padPos the pad position, one ofPAD_BEFORE_PREFIX
, - *PAD_AFTER_PREFIX
,PAD_BEFORE_SUFFIX
, or - *PAD_AFTER_SUFFIX
. - * @exception IllegalArgumentException if the pad position in unrecognized + * {@icu} Sets the position at which padding will take place. This is the location at which padding will be inserted + * if the result offormat()
is shorter than the format width. This has no effect unless padding is + * enabled. + * + * @param padPos + * the pad position, one ofPAD_BEFORE_PREFIX
,PAD_AFTER_PREFIX
, + *PAD_BEFORE_SUFFIX
, orPAD_AFTER_SUFFIX
. + * @exception IllegalArgumentException + * if the pad position in unrecognized * @see #setFormatWidth * @see #getFormatWidth * @see #setPadCharacter @@ -3540,7 +3436,7 @@ public class DecimalFormat extends NumberFormat { /** * {@icu} Returns whether or not scientific notation is used. - * + * * @return true if this object formats and parses scientific notation * @see #setScientificNotation * @see #getMinimumExponentDigits @@ -3554,13 +3450,13 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Sets whether or not scientific notation is used. When scientific notation is - * used, the effective maximum number of integer digits is <= 8. If the maximum number - * of integer digits is set to more than 8, the effective maximum will be 1. This - * allows this call to generate a 'default' scientific number format without - * additional changes. - * - * @param useScientific true if this object formats and parses scientific notation + * {@icu} Sets whether or not scientific notation is used. When scientific notation is used, the effective maximum + * number of integer digits is <= 8. If the maximum number of integer digits is set to more than 8, the effective + * maximum will be 1. This allows this call to generate a 'default' scientific number format without additional + * changes. + * + * @param useScientific + * true if this object formats and parses scientific notation * @see #isScientificNotation * @see #getMinimumExponentDigits * @see #setMinimumExponentDigits @@ -3574,7 +3470,7 @@ public class DecimalFormat extends NumberFormat { /** * {@icu} Returns the minimum exponent digits that will be shown. - * + * * @return the minimum exponent digits that will be shown * @see #setScientificNotation * @see #isScientificNotation @@ -3588,12 +3484,13 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Sets the minimum exponent digits that will be shown. This has no effect - * unless scientific notation is in use. - * - * @param minExpDig a value >= 1 indicating the fewest exponent - * digits that will be shown - * @exception IllegalArgumentException ifminExpDig
< 1 + * {@icu} Sets the minimum exponent digits that will be shown. This has no effect unless scientific notation is in + * use. + * + * @param minExpDig + * a value >= 1 indicating the fewest exponent digits that will be shown + * @exception IllegalArgumentException + * ifminExpDig
< 1 * @see #setScientificNotation * @see #isScientificNotation * @see #getMinimumExponentDigits @@ -3610,10 +3507,9 @@ public class DecimalFormat extends NumberFormat { /** * {@icu} Returns whether the exponent sign is always shown. - * - * @return true if the exponent is always prefixed with either the localized minus - * sign or the localized plus sign, false if only negative exponents are prefixed with - * the localized minus sign. + * + * @return true if the exponent is always prefixed with either the localized minus sign or the localized plus sign, + * false if only negative exponents are prefixed with the localized minus sign. * @see #setScientificNotation * @see #isScientificNotation * @see #setMinimumExponentDigits @@ -3626,12 +3522,11 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Sets whether the exponent sign is always shown. This has no effect unless - * scientific notation is in use. - * - * @param expSignAlways true if the exponent is always prefixed with either the - * localized minus sign or the localized plus sign, false if only negative exponents - * are prefixed with the localized minus sign. + * {@icu} Sets whether the exponent sign is always shown. This has no effect unless scientific notation is in use. + * + * @param expSignAlways + * true if the exponent is always prefixed with either the localized minus sign or the localized plus + * sign, false if only negative exponents are prefixed with the localized minus sign. * @see #setScientificNotation * @see #isScientificNotation * @see #setMinimumExponentDigits @@ -3644,10 +3539,9 @@ public class DecimalFormat extends NumberFormat { } /** - * Returns 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. - * + * Returns 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 NumberFormat#isGroupingUsed * @see DecimalFormatSymbols#getGroupingSeparator @@ -3658,10 +3552,9 @@ public class DecimalFormat extends NumberFormat { } /** - * Sets 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. - * + * Sets 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 NumberFormat#setGroupingUsed * @see DecimalFormatSymbols#setGroupingSeparator @@ -3672,14 +3565,13 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Returns the secondary grouping size. In some locales one grouping interval - * is used for the least significant integer digits (the primary grouping size), and - * another is used for all others (the secondary grouping size). A formatter - * supporting a secondary grouping size will return a positive integer unequal to the - * primary grouping size returned bygetGroupingSize()
. For example, if - * the primary grouping size is 4, and the secondary grouping size is 2, then the - * number 123456789 formats as "1,23,45,6789", and the pattern appears as "#,##,###0". - * + * {@icu} Returns the secondary grouping size. In some locales one grouping interval is used for the least + * significant integer digits (the primary grouping size), and another is used for all others (the secondary + * grouping size). A formatter supporting a secondary grouping size will return a positive integer unequal to the + * primary grouping size returned bygetGroupingSize()
. For example, if the primary grouping size is 4, + * and the secondary grouping size is 2, then the number 123456789 formats as "1,23,45,6789", and the pattern + * appears as "#,##,###0". + * * @return the secondary grouping size, or a value less than one if there is none * @see #setSecondaryGroupingSize * @see NumberFormat#isGroupingUsed @@ -3691,10 +3583,9 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Sets the secondary grouping size. If set to a value less than 1, then - * secondary grouping is turned off, and the primary grouping size is used for all - * intervals, not just the least significant. - * + * {@icu} Sets the secondary grouping size. If set to a value less than 1, then secondary grouping is turned off, + * and the primary grouping size is used for all intervals, not just the least significant. + * * @see #getSecondaryGroupingSize * @see NumberFormat#setGroupingUsed * @see DecimalFormatSymbols#setGroupingSeparator @@ -3706,7 +3597,7 @@ public class DecimalFormat extends NumberFormat { /** * {@icu} Returns the MathContext used by this format. - * + * * @return desired MathContext * @see #getMathContext * @stable ICU 4.2 @@ -3717,7 +3608,7 @@ public class DecimalFormat extends NumberFormat { /** * {@icu} Returns the MathContext used by this format. - * + * * @return desired MathContext * @see #getMathContext * @stable ICU 4.2 @@ -3734,8 +3625,9 @@ public class DecimalFormat extends NumberFormat { /** * {@icu} Sets the MathContext used by this format. - * - * @param newValue desired MathContext + * + * @param newValue + * desired MathContext * @see #getMathContext * @stable ICU 4.2 */ @@ -3745,21 +3637,23 @@ public class DecimalFormat extends NumberFormat { /** * {@icu} Sets the MathContext used by this format. - * - * @param newValue desired MathContext + * + * @param newValue + * desired MathContext * @see #getMathContext * @stable ICU 4.2 */ public void setMathContext(java.math.MathContext newValue) { mathContext = new MathContext(newValue.getPrecision(), MathContext.SCIENTIFIC, false, - (newValue.getRoundingMode()).ordinal()); + (newValue.getRoundingMode()).ordinal()); } /** - * Returns the behavior of the decimal separator with integers. (The decimal - * separator will always appear with decimals.)Example: Decimal ON: 12345 -> - * 12345.; OFF: 12345 -> 12345 - * + * Returns the behavior of the decimal separator with integers. (The decimal separator will always appear with + * decimals.) + *
+ * Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345 + * * @stable ICU 2.0 */ public boolean isDecimalSeparatorAlwaysShown() { @@ -3767,17 +3661,17 @@ public class DecimalFormat extends NumberFormat { } /** - * Sets the behavior of the decimal separator with integers. (The decimal separator - * will always appear with decimals.) - * - *
This only affects formatting, and only where there might be no digits after the - * decimal point, e.g., if true, 3456.00 -> "3,456." if false, 3456.00 -> "3456" This - * is independent of parsing. If you want parsing to stop at the decimal point, use - * setParseIntegerOnly. - * + * Sets the behavior of the decimal separator with integers. (The decimal separator will always appear with + * decimals.) + * + *
+ * This only affects formatting, and only where there might be no digits after the decimal point, e.g., if true, + * 3456.00 -> "3,456." if false, 3456.00 -> "3456" This is independent of parsing. If you want parsing to stop at + * the decimal point, use setParseIntegerOnly. + * *
* Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345 - * + * * @stable ICU 2.0 */ public void setDecimalSeparatorAlwaysShown(boolean newValue) { @@ -3785,12 +3679,10 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Returns a copy of the CurrencyPluralInfo used by this format. It might - * return null if the decimal format is not a plural type currency decimal - * format. Plural type currency decimal format means either the pattern in the decimal - * format contains 3 currency signs, or the decimal format is initialized with - * PLURALCURRENCYSTYLE. - * + * {@icu} Returns a copy of the CurrencyPluralInfo used by this format. It might return null if the decimal format + * is not a plural type currency decimal format. Plural type currency decimal format means either the pattern in the + * decimal format contains 3 currency signs, or the decimal format is initialized with PLURALCURRENCYSTYLE. + * * @return desired CurrencyPluralInfo * @see CurrencyPluralInfo * @stable ICU 4.2 @@ -3798,18 +3690,17 @@ public class DecimalFormat extends NumberFormat { public CurrencyPluralInfo getCurrencyPluralInfo() { try { // don't allow multiple references - return currencyPluralInfo == null ? null : - (CurrencyPluralInfo) currencyPluralInfo.clone(); + return currencyPluralInfo == null ? null : (CurrencyPluralInfo) currencyPluralInfo.clone(); } catch (Exception foo) { return null; // should never happen } } /** - * {@icu} Sets the CurrencyPluralInfo used by this format. The format uses a copy of - * the provided information. - * - * @param newInfo desired CurrencyPluralInfo + * {@icu} Sets the CurrencyPluralInfo used by this format. The format uses a copy of the provided information. + * + * @param newInfo + * desired CurrencyPluralInfo * @see CurrencyPluralInfo * @stable ICU 4.2 */ @@ -3820,6 +3711,7 @@ public class DecimalFormat extends NumberFormat { /** * Overrides clone. + * * @stable ICU 2.0 */ @Override @@ -3832,9 +3724,10 @@ public class DecimalFormat extends NumberFormat { other.currencyPluralInfo = (CurrencyPluralInfo) currencyPluralInfo.clone(); } other.attributes = new ArrayList
(); // #9240 + other.currencyUsage = currencyUsage; // TODO: We need to figure out whether we share a single copy of DigitList by - // multiple cloned copies. format/subformat are designed to use a single + // multiple cloned copies. format/subformat are designed to use a single // instance, but parse/subparse implementation is not. return other; } catch (Exception e) { @@ -3844,6 +3737,7 @@ public class DecimalFormat extends NumberFormat { /** * Overrides equals. + * * @stable ICU 2.0 */ @Override @@ -3858,11 +3752,10 @@ public class DecimalFormat extends NumberFormat { // posSuffixPattern, negPrefixPattern, negSuffixPattern. [Richard/GCL] // following are added to accomodate changes for currency plural format. return currencySignCount == other.currencySignCount - && (style != NumberFormat.PLURALCURRENCYSTYLE || - equals(posPrefixPattern, other.posPrefixPattern) - && equals(posSuffixPattern, other.posSuffixPattern) - && equals(negPrefixPattern, other.negPrefixPattern) - && equals(negSuffixPattern, other.negSuffixPattern)) + && (style != NumberFormat.PLURALCURRENCYSTYLE || equals(posPrefixPattern, other.posPrefixPattern) + && equals(posSuffixPattern, other.posSuffixPattern) + && equals(negPrefixPattern, other.negPrefixPattern) + && equals(negSuffixPattern, other.negSuffixPattern)) && multiplier == other.multiplier && groupingSize == other.groupingSize && groupingSize2 == other.groupingSize2 @@ -3871,9 +3764,9 @@ public class DecimalFormat extends NumberFormat { && (!useExponentialNotation || minExponentDigits == other.minExponentDigits) && useSignificantDigits == other.useSignificantDigits && (!useSignificantDigits || minSignificantDigits == other.minSignificantDigits - && maxSignificantDigits == other.maxSignificantDigits) - && symbols.equals(other.symbols) - && Utility.objectEquals(currencyPluralInfo, other.currencyPluralInfo); + && maxSignificantDigits == other.maxSignificantDigits) && symbols.equals(other.symbols) + && Utility.objectEquals(currencyPluralInfo, other.currencyPluralInfo) + && currencyUsage.equals(other.currencyUsage); } // method to unquote the strings and compare @@ -3906,9 +3799,9 @@ public class DecimalFormat extends NumberFormat { // buf.append("posSuffixPattern: '" + posSuffixPattern + "'\n"); // buf.append("positiveSuffix: '" + positiveSuffix + "'\n"); // buf.append("negPrefixPattern: '" + - // com.ibm.icu.impl.Utility.format1ForSource(negPrefixPattern) + "'\n"); + // com.ibm.icu.impl.Utility.format1ForSource(negPrefixPattern) + "'\n"); // buf.append("negativePrefix: '" + - // com.ibm.icu.impl.Utility.format1ForSource(negativePrefix) + "'\n"); + // com.ibm.icu.impl.Utility.format1ForSource(negativePrefix) + "'\n"); // buf.append("negSuffixPattern: '" + negSuffixPattern + "'\n"); // buf.append("negativeSuffix: '" + negativeSuffix + "'\n"); // buf.append("multiplier: '" + multiplier + "'\n"); @@ -3925,6 +3818,7 @@ public class DecimalFormat extends NumberFormat { /** * Overrides hashCode. + * * @stable ICU 2.0 */ @Override @@ -3934,17 +3828,16 @@ public class DecimalFormat extends NumberFormat { } /** - * Synthesizes a pattern string that represents the current state of this Format - * object. - * + * Synthesizes a pattern string that represents the current state of this Format object. + * * @see #applyPattern * @stable ICU 2.0 */ public String toPattern() { if (style == NumberFormat.PLURALCURRENCYSTYLE) { // the prefix or suffix pattern might not be defined yet, so they can not be - // synthesized, instead, get them directly. but it might not be the actual - // pattern used in formatting. the actual pattern used in formatting depends + // synthesized, instead, get them directly. but it might not be the actual + // pattern used in formatting. the actual pattern used in formatting depends // on the formatted number's plural count. return formatPattern; } @@ -3952,9 +3845,8 @@ public class DecimalFormat extends NumberFormat { } /** - * Synthesizes a localized pattern string that represents the current state of this - * Format object. - * + * Synthesizes a localized pattern string that represents the current state of this Format object. + * * @see #applyPattern * @stable ICU 2.0 */ @@ -3966,15 +3858,12 @@ public class DecimalFormat extends NumberFormat { } /** - * Expands the affix pattern strings into the expanded affix strings. If any affix - * pattern string is null, do not expand it. This method should be called any time the - * symbols or the affix patterns change in order to keep the expanded affix strings up - * to date. This method also will be called before formatting if format currency - * plural names, since the plural name is not a static one, it is based on the - * currency plural count, the affix will be known only after the currency plural count - * is know. In which case, the parameter 'pluralCount' will be a non-null currency - * plural count. In all other cases, the 'pluralCount' is null, which means it is not - * needed. + * Expands the affix pattern strings into the expanded affix strings. If any affix pattern string is null, do not + * expand it. This method should be called any time the symbols or the affix patterns change in order to keep the + * expanded affix strings up to date. This method also will be called before formatting if format currency plural + * names, since the plural name is not a static one, it is based on the currency plural count, the affix will be + * known only after the currency plural count is know. In which case, the parameter 'pluralCount' will be a non-null + * currency plural count. In all other cases, the 'pluralCount' is null, which means it is not needed. */ // Bug 4212072 [Richard/GCL] private void expandAffixes(String pluralCount) { @@ -4003,40 +3892,37 @@ public class DecimalFormat extends NumberFormat { } /** - * Expands an affix pattern into an affix string. All characters in the pattern are - * literal unless bracketed by QUOTEs. The following characters outside QUOTE are - * recognized: PATTERN_PERCENT, PATTERN_PER_MILLE, PATTERN_MINUS, and - * CURRENCY_SIGN. If CURRENCY_SIGN is doubled, it is interpreted as an international - * currency sign. If CURRENCY_SIGN is tripled, it is interpreted as currency plural - * long names, such as "US Dollars". Any other character outside QUOTE represents - * itself. Quoted text must be well-formed. - * - * This method is used in two distinct ways. First, it is used to expand the stored - * affix patterns into actual affixes. For this usage, doFormat must be false. Second, - * it is used to expand the stored affix patterns given a specific number (doFormat == - * true), for those rare cases in which a currency format references a ChoiceFormat + * Expands an affix pattern into an affix string. All characters in the pattern are literal unless bracketed by + * QUOTEs. The following characters outside QUOTE are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE, PATTERN_MINUS, + * and CURRENCY_SIGN. If CURRENCY_SIGN is doubled, it is interpreted as an international currency sign. If + * CURRENCY_SIGN is tripled, it is interpreted as currency plural long names, such as "US Dollars". Any other + * character outside QUOTE represents itself. Quoted text must be well-formed. + * + * This method is used in two distinct ways. First, it is used to expand the stored affix patterns into actual + * affixes. For this usage, doFormat must be false. Second, it is used to expand the stored affix patterns given a + * specific number (doFormat == true), for those rare cases in which a currency format references a ChoiceFormat * (e.g., en_IN display name for INR). The number itself is taken from digitList. - * - * When used in the first way, this method has a side effect: It sets currencyChoice - * to a ChoiceFormat object, if the currency's display name in this locale is a - * ChoiceFormat pattern (very rare). It only does this if currencyChoice is null to - * start with. - * - * @param pattern the non-null, possibly empty pattern - * @param pluralCount the plural count. It is only used for currency plural format. In - * which case, it is the plural count of the currency amount. For example, in en_US, - * it is the singular "one", or the plural "other". For all other cases, it is null, - * and is not being used. - * @param buffer a scratch StringBuffer; its contents will be lost - * @param doFormat if false, then the pattern will be expanded, and if a currency - * symbol is encountered that expands to a ChoiceFormat, the currencyChoice member - * variable will be initialized if it is null. If doFormat is true, then it is assumed - * that the currencyChoice has been created, and it will be used to format the value - * in digitList. + * + * When used in the first way, this method has a side effect: It sets currencyChoice to a ChoiceFormat object, if + * the currency's display name in this locale is a ChoiceFormat pattern (very rare). It only does this if + * currencyChoice is null to start with. + * + * @param pattern + * the non-null, possibly empty pattern + * @param pluralCount + * the plural count. It is only used for currency plural format. In which case, it is the plural count of + * the currency amount. For example, in en_US, it is the singular "one", or the plural "other". For all + * other cases, it is null, and is not being used. + * @param buffer + * a scratch StringBuffer; its contents will be lost + * @param doFormat + * if false, then the pattern will be expanded, and if a currency symbol is encountered that expands to a + * ChoiceFormat, the currencyChoice member variable will be initialized if it is null. If doFormat is + * true, then it is assumed that the currencyChoice has been created, and it will be used to format the + * value in digitList. */ // Bug 4212072 [Richard/GCL] - private void expandAffix(String pattern, String pluralCount, StringBuffer buffer, - boolean doFormat) { + private void expandAffix(String pattern, String pluralCount, StringBuffer buffer, boolean doFormat) { buffer.setLength(0); for (int i = 0; i < pattern.length();) { char c = pattern.charAt(i++); @@ -4085,16 +3971,15 @@ public class DecimalFormat extends NumberFormat { Currency currency = getCurrency(); if (currency != null) { // plural name is only needed when pluralCount != null, which means - // when formatting currency plural names. For other cases, + // when formatting currency plural names. For other cases, // pluralCount == null, and plural names are not needed. if (plural && pluralCount != null) { boolean isChoiceFormat[] = new boolean[1]; - s = currency.getName(symbols.getULocale(), Currency.PLURAL_LONG_NAME, - pluralCount, isChoiceFormat); + s = currency.getName(symbols.getULocale(), Currency.PLURAL_LONG_NAME, pluralCount, + isChoiceFormat); } else if (!intl) { boolean isChoiceFormat[] = new boolean[1]; - s = currency.getName(symbols.getULocale(), Currency.SYMBOL_NAME, - isChoiceFormat); + s = currency.getName(symbols.getULocale(), Currency.SYMBOL_NAME, isChoiceFormat); if (isChoiceFormat[0]) { // Two modes here: If doFormat is false, we set up // currencyChoice. If doFormat is true, we use the previously @@ -4123,8 +4008,7 @@ public class DecimalFormat extends NumberFormat { s = currency.getCurrencyCode(); } } else { - s = intl ? symbols.getInternationalCurrencySymbol() : - symbols.getCurrencySymbol(); + s = intl ? symbols.getInternationalCurrencySymbol() : symbols.getCurrencySymbol(); } buffer.append(s); continue; @@ -4145,14 +4029,13 @@ public class DecimalFormat extends NumberFormat { /** * Append an affix to the given StringBuffer. - * + * * @param buf * buffer to append to * @param isNegative * @param isPrefix */ - private int appendAffix(StringBuffer buf, boolean isNegative, boolean isPrefix, - boolean parseAttr) { + private int appendAffix(StringBuffer buf, boolean isNegative, boolean isPrefix, boolean parseAttr) { if (currencyChoice != null) { String affixPat = null; if (isPrefix) { @@ -4188,12 +4071,11 @@ public class DecimalFormat extends NumberFormat { } /** - * [Spark/CDL] This is a newly added method, used to add attributes for prefix and - * suffix. + * [Spark/CDL] This is a newly added method, used to add attributes for prefix and suffix. */ private void formatAffix2Attribute(String affix, int begin, int end) { // [Spark/CDL] It is the invoker's responsibility to ensure that, before the - // invocation of this method, attributes is not null. if( attributes == null ) + // invocation of this method, attributes is not null. if( attributes == null ) // return; if (affix.indexOf(symbols.getCurrencySymbol()) > -1) { addAttribute(Field.CURRENCY, begin, end); @@ -4218,12 +4100,12 @@ public class DecimalFormat extends NumberFormat { /** * Formats the object to an attributed string, and return the corresponding iterator. - * + * * @stable ICU 3.6 */ @Override public AttributedCharacterIterator formatToCharacterIterator(Object obj) { - return formatToCharacterIterator(obj, NULL_UNIT); + return formatToCharacterIterator(obj, NULL_UNIT); } AttributedCharacterIterator formatToCharacterIterator(Object obj, Unit unit) { @@ -4236,8 +4118,7 @@ public class DecimalFormat extends NumberFormat { if (obj instanceof BigInteger) { format((BigInteger) number, text, new FieldPosition(0), true); } else if (obj instanceof java.math.BigDecimal) { - format((java.math.BigDecimal) number, text, new FieldPosition(0) - , true); + format((java.math.BigDecimal) number, text, new FieldPosition(0), true); } else if (obj instanceof Double) { format(number.doubleValue(), text, new FieldPosition(0), true); } else if (obj instanceof Integer || obj instanceof Long) { @@ -4262,8 +4143,7 @@ public class DecimalFormat extends NumberFormat { /** * Appends an affix pattern to the given StringBuffer. Localize unquoted specials. */ - private void appendAffixPattern(StringBuffer buffer, boolean isNegative, boolean isPrefix, - boolean localized) { + private void appendAffixPattern(StringBuffer buffer, boolean isNegative, boolean isPrefix, boolean localized) { String affixPat = null; if (isPrefix) { affixPat = isNegative ? negPrefixPattern : posPrefixPattern; @@ -4346,11 +4226,8 @@ public class DecimalFormat extends NumberFormat { int roundingDecimalPos = 0; // Pos of decimal in roundingDigits String roundingDigits = null; int padPos = (formatWidth > 0) ? padPosition : -1; - String padSpec = (formatWidth > 0) - ? new StringBuffer(2).append(localized - ? symbols.getPadEscape() - : PATTERN_PAD_ESCAPE).append(pad).toString() - : null; + String padSpec = (formatWidth > 0) ? new StringBuffer(2) + .append(localized ? symbols.getPadEscape() : PATTERN_PAD_ESCAPE).append(pad).toString() : null; if (roundingIncrementICU != null) { i = roundingIncrementICU.scale(); roundingDigits = roundingIncrementICU.movePointRight(i).toString(); @@ -4413,14 +4290,12 @@ public class DecimalFormat extends NumberFormat { } if (!useSigDig) { if (getMaximumFractionDigits() > 0 || decimalSeparatorAlwaysShown) { - result.append(localized ? symbols.getDecimalSeparator() : - PATTERN_DECIMAL_SEPARATOR); + result.append(localized ? symbols.getDecimalSeparator() : PATTERN_DECIMAL_SEPARATOR); } int pos = roundingDecimalPos; for (i = 0; i < getMaximumFractionDigits(); ++i) { if (roundingDigits != null && pos < roundingDigits.length()) { - result.append(pos < 0 ? zero : - (char) (roundingDigits.charAt(pos) - '0' + zero)); + result.append(pos < 0 ? zero : (char) (roundingDigits.charAt(pos) - '0' + zero)); ++pos; continue; } @@ -4444,9 +4319,8 @@ public class DecimalFormat extends NumberFormat { int add = formatWidth - result.length() + sub0Start - - ((part == 0) - ? positivePrefix.length() + positiveSuffix.length() - : negativePrefix.length() + negativeSuffix.length()); + - ((part == 0) ? positivePrefix.length() + positiveSuffix.length() : negativePrefix.length() + + negativeSuffix.length()); while (add > 0) { result.insert(sub0Start, digit); ++maxDig; @@ -4469,8 +4343,7 @@ public class DecimalFormat extends NumberFormat { result.append(padSpec); } if (part == 0) { - if (negativeSuffix.equals(positiveSuffix) && - negativePrefix.equals(PATTERN_MINUS + positivePrefix)) { + if (negativeSuffix.equals(positiveSuffix) && negativePrefix.equals(PATTERN_MINUS + positivePrefix)) { break; } else { result.append(localized ? symbols.getPatternSeparator() : PATTERN_SEPARATOR); @@ -4481,24 +4354,27 @@ public class DecimalFormat extends NumberFormat { } /** - * Applies the given pattern to this Format object. A pattern is a short-hand - * specification for the various formatting properties. These properties can also be - * changed individually through the various setter methods. - * - * There is no limit to integer digits are set by this routine, since that is the - * typical end-user desire; use setMaximumInteger if you want to set a real value. For - * negative numbers, use a second pattern, separated by a semicolon - * - *
Example "#,#00.0#" -> 1,234.56 - * - *
This means a minimum of 2 integer digits, 1 fraction digit, and a maximum of 2 - * fraction digits. - * - *
Example: "#,#00.0#;(#,#00.0#)" for negatives in parentheses. - * - *
In negative patterns, the minimum and maximum counts are ignored; these are - * presumed to be set in the positive pattern. - * + * Applies the given pattern to this Format object. A pattern is a short-hand specification for the various + * formatting properties. These properties can also be changed individually through the various setter methods. + * + *
+ * There is no limit to integer digits are set by this routine, since that is the typical end-user desire; use + * setMaximumInteger if you want to set a real value. For negative numbers, use a second pattern, separated by a + * semicolon + * + *
+ * Example "#,#00.0#" -> 1,234.56 + * + *
+ * This means a minimum of 2 integer digits, 1 fraction digit, and a maximum of 2 fraction digits. + * + *
+ * Example: "#,#00.0#;(#,#00.0#)" for negatives in parentheses. + * + *
+ * In negative patterns, the minimum and maximum counts are ignored; these are presumed to be set in the positive + * pattern. + * * @stable ICU 2.0 */ public void applyPattern(String pattern) { @@ -4506,25 +4382,28 @@ public class DecimalFormat extends NumberFormat { } /** - * Applies the given pattern to this Format object. The pattern is assumed to be in a - * localized notation. A pattern is a short-hand specification for the various - * formatting properties. These properties can also be changed individually through - * the various setter methods. - * - *
There is no limit to integer digits are set by this routine, since that is the - * typical end-user desire; use setMaximumInteger if you want to set a real value. For - * negative numbers, use a second pattern, separated by a semicolon - * - *
Example "#,#00.0#" -> 1,234.56 - * - *
This means a minimum of 2 integer digits, 1 fraction digit, and a maximum of 2 - * fraction digits. - * - *
Example: "#,#00.0#;(#,#00.0#)" for negatives in parantheses. - * - *
In negative patterns, the minimum and maximum counts are ignored; these are - * presumed to be set in the positive pattern. - * + * Applies the given pattern to this Format object. The pattern is assumed to be in a localized notation. A pattern + * is a short-hand specification for the various formatting properties. These properties can also be changed + * individually through the various setter methods. + * + *
+ * There is no limit to integer digits are set by this routine, since that is the typical end-user desire; use + * setMaximumInteger if you want to set a real value. For negative numbers, use a second pattern, separated by a + * semicolon + * + *
+ * Example "#,#00.0#" -> 1,234.56 + * + *
+ * This means a minimum of 2 integer digits, 1 fraction digit, and a maximum of 2 fraction digits. + * + *
+ * Example: "#,#00.0#;(#,#00.0#)" for negatives in parantheses. + * + *
+ * In negative patterns, the minimum and maximum counts are ignored; these are presumed to be set in the positive + * pattern. + * * @stable ICU 2.0 */ public void applyLocalizedPattern(String pattern) { @@ -4541,7 +4420,7 @@ public class DecimalFormat extends NumberFormat { private void expandAffixAdjustWidth(String pluralCount) { // Bug 4212072 Update the affix strings according to symbols in order to keep the - // affix strings up to date. [Richard/GCL] + // affix strings up to date. [Richard/GCL] expandAffixes(pluralCount); // Now that we have the actual prefix and suffix, fix up formatWidth @@ -4726,9 +4605,8 @@ public class DecimalFormat extends NumberFormat { // 1. Require at least one mantissa pattern digit // 2. Disallow "#+ @" in mantissa // 3. Require at least one exponent pattern digit - if (((digitLeftCount + zeroDigitCount) < 1 && - (sigDigitCount + digitRightCount) < 1) - || (sigDigitCount > 0 && digitLeftCount > 0) || expDigits < 1) { + if (((digitLeftCount + zeroDigitCount) < 1 && (sigDigitCount + digitRightCount) < 1) + || (sigDigitCount > 0 && digitLeftCount > 0) || expDigits < 1) { patternError("Malformed exponential", pattern); } } @@ -4774,16 +4652,14 @@ public class DecimalFormat extends NumberFormat { } else if (ch == CURRENCY_SIGN) { // Use lookahead to determine if the currency sign is // doubled or not. - boolean doubled = (pos + 1) < pattern.length() && - pattern.charAt(pos + 1) == CURRENCY_SIGN; + boolean doubled = (pos + 1) < pattern.length() && pattern.charAt(pos + 1) == CURRENCY_SIGN; // Bug 4212072 To meet the need of expandAffix(String, // StirngBuffer) [Richard/GCL] if (doubled) { ++pos; // Skip over the doubled character affix.append(ch); // append two: one here, one below - if ((pos + 1) < pattern.length() && - pattern.charAt(pos + 1) == CURRENCY_SIGN) { + if ((pos + 1) < pattern.length() && pattern.charAt(pos + 1) == CURRENCY_SIGN) { ++pos; // Skip over the tripled character affix.append(ch); // append again currencySignCnt = CURRENCY_SIGN_COUNT_IN_PLURAL_FORMAT; @@ -4885,8 +4761,7 @@ public class DecimalFormat extends NumberFormat { // yields a minimum integer digits of zero, which allows proper round-trip // patterns. We don't want "#" to become "#0" when toPattern() is called (even // though that's what it really is, semantically). - if (zeroDigitCount == 0 && sigDigitCount == 0 && - digitLeftCount > 0 && decimalPos >= 0) { + if (zeroDigitCount == 0 && sigDigitCount == 0 && digitLeftCount > 0 && decimalPos >= 0) { // Handle "###.###" and "###." and ".###" int n = decimalPos; if (n == 0) @@ -4898,14 +4773,9 @@ public class DecimalFormat extends NumberFormat { // Do syntax checking on the digits, decimal points, and quotes. if ((decimalPos < 0 && digitRightCount > 0 && sigDigitCount == 0) - || (decimalPos >= 0 - && (sigDigitCount > 0 - || decimalPos < digitLeftCount - || decimalPos > (digitLeftCount + zeroDigitCount))) - || groupingCount == 0 - || groupingCount2 == 0 - || (sigDigitCount > 0 && zeroDigitCount > 0) - || subpart > 2) { // subpart > 2 == unmatched quote + || (decimalPos >= 0 && (sigDigitCount > 0 || decimalPos < digitLeftCount || decimalPos > (digitLeftCount + zeroDigitCount))) + || groupingCount == 0 || groupingCount2 == 0 || (sigDigitCount > 0 && zeroDigitCount > 0) + || subpart > 2) { // subpart > 2 == unmatched quote patternError("Malformed pattern", pattern); } @@ -4954,17 +4824,13 @@ public class DecimalFormat extends NumberFormat { // Upper limit on integer and fraction digits for a Java double // [Richard/GCL] - setMaximumIntegerDigits(useExponentialNotation ? digitLeftCount + minInt : - DOUBLE_INTEGER_DIGITS); - _setMaximumFractionDigits(decimalPos >= 0 ? - (digitTotalCount - decimalPos) : 0); - setMinimumFractionDigits(decimalPos >= 0 ? - (digitLeftCount + zeroDigitCount - decimalPos) : 0); + setMaximumIntegerDigits(useExponentialNotation ? digitLeftCount + minInt : DOUBLE_INTEGER_DIGITS); + _setMaximumFractionDigits(decimalPos >= 0 ? (digitTotalCount - decimalPos) : 0); + setMinimumFractionDigits(decimalPos >= 0 ? (digitLeftCount + zeroDigitCount - decimalPos) : 0); } setGroupingUsed(groupingCount > 0); this.groupingSize = (groupingCount > 0) ? groupingCount : 0; - this.groupingSize2 = (groupingCount2 > 0 && groupingCount2 != groupingCount) - ? groupingCount2 : 0; + this.groupingSize2 = (groupingCount2 > 0 && groupingCount2 != groupingCount) ? groupingCount2 : 0; this.multiplier = multpl; setDecimalSeparatorAlwaysShown(decimalPos == 0 || decimalPos == digitTotalCount); if (padPos >= 0) { @@ -4998,7 +4864,6 @@ public class DecimalFormat extends NumberFormat { } } - // Bug 4140009 Process the empty pattern [Richard/GCL] if (pattern.length() == 0) { posPrefixPattern = posSuffixPattern = ""; @@ -5014,9 +4879,7 @@ public class DecimalFormat extends NumberFormat { // Bug 4212072 To meet the need of expandAffix(String, StirngBuffer) [Richard/GCL] - if (!gotNegative || - (negPrefixPattern.equals(posPrefixPattern) - && negSuffixPattern.equals(posSuffixPattern))) { + if (!gotNegative || (negPrefixPattern.equals(posPrefixPattern) && negSuffixPattern.equals(posSuffixPattern))) { negSuffixPattern = posSuffixPattern; negPrefixPattern = PATTERN_MINUS + posPrefixPattern; } @@ -5030,34 +4893,31 @@ public class DecimalFormat extends NumberFormat { // by the currency Currency theCurrency = getCurrency(); if (theCurrency != null) { - setRoundingIncrement(theCurrency.getRoundingIncrement()); - int d = theCurrency.getDefaultFractionDigits(); + setRoundingIncrement(theCurrency.getRoundingIncrement(currencyUsage)); + int d = theCurrency.getDefaultFractionDigits(currencyUsage); setMinimumFractionDigits(d); _setMaximumFractionDigits(d); } // initialize currencyPluralInfo if needed - if (currencySignCount == CURRENCY_SIGN_COUNT_IN_PLURAL_FORMAT - && currencyPluralInfo == null) { + if (currencySignCount == CURRENCY_SIGN_COUNT_IN_PLURAL_FORMAT && currencyPluralInfo == null) { currencyPluralInfo = new CurrencyPluralInfo(symbols.getULocale()); } } resetActualRounding(); } - private void patternError(String msg, String pattern) { throw new IllegalArgumentException(msg + " in pattern \"" + pattern + '"'); } - // Rewrite the following 4 "set" methods Upper limit on integer and fraction digits // for a Java double [Richard/GCL] /** - * Sets the maximum number of digits allowed in the integer portion of a number. This - * override limits the integer digit count to 309. - * + * Sets the maximum number of digits allowed in the integer portion of a number. This override limits the integer + * digit count to 309. + * * @see NumberFormat#setMaximumIntegerDigits * @stable ICU 2.0 */ @@ -5067,9 +4927,9 @@ public class DecimalFormat extends NumberFormat { } /** - * Sets the minimum number of digits allowed in the integer portion of a number. This - * override limits the integer digit count to 309. - * + * Sets the minimum number of digits allowed in the integer portion of a number. This override limits the integer + * digit count to 309. + * * @see NumberFormat#setMinimumIntegerDigits * @stable ICU 2.0 */ @@ -5079,10 +4939,9 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Returns the minimum number of significant digits that will be - * displayed. This value has no effect unless {@link #areSignificantDigitsUsed()} - * returns true. - * + * {@icu} Returns the minimum number of significant digits that will be displayed. This value has no effect unless + * {@link #areSignificantDigitsUsed()} returns true. + * * @return the fewest significant digits that will be shown * @stable ICU 3.0 */ @@ -5091,10 +4950,9 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Returns the maximum number of significant digits that will be - * displayed. This value has no effect unless {@link #areSignificantDigitsUsed()} - * returns true. - * + * {@icu} Returns the maximum number of significant digits that will be displayed. This value has no effect unless + * {@link #areSignificantDigitsUsed()} returns true. + * * @return the most significant digits that will be shown * @stable ICU 3.0 */ @@ -5103,13 +4961,13 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Sets the minimum number of significant digits that will be displayed. If - *
min
is less than one then it is set to one. If the maximum significant - * digits count is less thanmin
, then it is set tomin
. - * This function also enables the use of significant digits by this formatter - + * {@icu} Sets the minimum number of significant digits that will be displayed. Ifmin
is less than one + * then it is set to one. If the maximum significant digits count is less thanmin
, then it is set to + *min
. This function also enables the use of significant digits by this formatter - * {@link #areSignificantDigitsUsed()} will return true. - * - * @param min the fewest significant digits to be shown + * + * @param min + * the fewest significant digits to be shown * @stable ICU 3.0 */ public void setMinimumSignificantDigits(int min) { @@ -5124,13 +4982,13 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Sets the maximum number of significant digits that will be displayed. If - *max
is less than one then it is set to one. If the minimum significant - * digits count is greater thanmax
, then it is set tomax
. - * This function also enables the use of significant digits by this formatter - + * {@icu} Sets the maximum number of significant digits that will be displayed. Ifmax
is less than one + * then it is set to one. If the minimum significant digits count is greater thanmax
, then it is set + * tomax
. This function also enables the use of significant digits by this formatter - * {@link #areSignificantDigitsUsed()} will return true. - * - * @param max the most significant digits to be shown + * + * @param max + * the most significant digits to be shown * @stable ICU 3.0 */ public void setMaximumSignificantDigits(int max) { @@ -5145,9 +5003,8 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Returns true if significant digits are in use or false if integer and - * fraction digit counts are in use. - * + * {@icu} Returns true if significant digits are in use or false if integer and fraction digit counts are in use. + * * @return true if significant digits are in use * @stable ICU 3.0 */ @@ -5156,11 +5013,10 @@ public class DecimalFormat extends NumberFormat { } /** - * {@icu} Sets whether significant digits are in use, or integer and fraction digit - * counts are in use. - * - * @param useSignificantDigits true to use significant digits, or false to use integer - * and fraction digit counts + * {@icu} Sets whether significant digits are in use, or integer and fraction digit counts are in use. + * + * @param useSignificantDigits + * true to use significant digits, or false to use integer and fraction digit counts * @stable ICU 3.0 */ public void setSignificantDigitsUsed(boolean useSignificantDigits) { @@ -5168,12 +5024,12 @@ public class DecimalFormat extends NumberFormat { } /** - * Sets the Currency object used to display currency amounts. This takes - * effect immediately, if this format is a currency format. If this format is not a - * currency format, then the currency object is used if and when this object becomes a - * currency format through the application of a new pattern. - * - * @param theCurrency new currency object to use. Must not be null. + * Sets the Currency object used to display currency amounts. This takes effect immediately, if this format + * is a currency format. If this format is not a currency format, then the currency object is used if and when this + * object becomes a currency format through the application of a new pattern. + * + * @param theCurrency + * new currency object to use. Must not be null. * @stable ICU 2.2 */ @Override @@ -5182,22 +5038,20 @@ public class DecimalFormat extends NumberFormat { // encode the currency symbol for the given currency in our // locale, and adjust the decimal digits and rounding for the // given currency. - super.setCurrency(theCurrency); if (theCurrency != null) { boolean[] isChoiceFormat = new boolean[1]; - String s = theCurrency.getName(symbols.getULocale(), - Currency.SYMBOL_NAME, isChoiceFormat); + String s = theCurrency.getName(symbols.getULocale(), Currency.SYMBOL_NAME, isChoiceFormat); symbols.setCurrency(theCurrency); symbols.setCurrencySymbol(s); } if (currencySignCount != CURRENCY_SIGN_COUNT_ZERO) { if (theCurrency != null) { - setRoundingIncrement(theCurrency.getRoundingIncrement()); - int d = theCurrency.getDefaultFractionDigits(); + setRoundingIncrement(theCurrency.getRoundingIncrement(currencyUsage)); + int d = theCurrency.getDefaultFractionDigits(currencyUsage); setMinimumFractionDigits(d); - setMaximumFractionDigits(d); + _setMaximumFractionDigits(d); } if (currencySignCount != CURRENCY_SIGN_COUNT_IN_PLURAL_FORMAT) { // This is not necessary for plural format type @@ -5208,9 +5062,39 @@ public class DecimalFormat extends NumberFormat { } /** - * Returns the currency in effect for this formatter. Subclasses should override this - * method as needed. Unlike getCurrency(), this method should never return null. - * + * Sets the Currency Usage object used to display currency. This takes effect immediately, if this format + * is a currency format. + * + * @param newUsage + * new currency context object to use. + * @draft ICU 54 + */ + public void setCurrencyUsage(CurrencyUsage newUsage) { + currencyUsage = newUsage; + Currency theCurrency = this.getCurrency(); + + // We set rounding/digit based on currency context + if (theCurrency != null) { + setRoundingIncrement(theCurrency.getRoundingIncrement(currencyUsage)); + int d = theCurrency.getDefaultFractionDigits(currencyUsage); + setMinimumFractionDigits(d); + _setMaximumFractionDigits(d); + } + } + + /** + * Returns the Currency Usage object used to display currency + * + * @draft ICU 54 + */ + public CurrencyUsage getCurrencyUsage() { + return currencyUsage; + } + + /** + * Returns the currency in effect for this formatter. Subclasses should override this method as needed. Unlike + * getCurrency(), this method should never return null. + * * @internal * @deprecated This API is ICU internal only. */ @@ -5225,9 +5109,9 @@ public class DecimalFormat extends NumberFormat { } /** - * Sets the maximum number of digits allowed in the fraction portion of a number. This - * override limits the fraction digit count to 340. - * + * Sets the maximum number of digits allowed in the fraction portion of a number. This override limits the fraction + * digit count to 340. + * * @see NumberFormat#setMaximumFractionDigits * @stable ICU 2.0 */ @@ -5238,17 +5122,17 @@ public class DecimalFormat extends NumberFormat { } /* - * Internal method for DecimalFormat, setting maximum fractional digits - * without triggering actual rounding recalculated. + * Internal method for DecimalFormat, setting maximum fractional digits without triggering actual rounding + * recalculated. */ private void _setMaximumFractionDigits(int newValue) { super.setMaximumFractionDigits(Math.min(newValue, DOUBLE_FRACTION_DIGITS)); } /** - * Sets the minimum number of digits allowed in the fraction portion of a number. This - * override limits the fraction digit count to 340. - * + * Sets the minimum number of digits allowed in the fraction portion of a number. This override limits the fraction + * digit count to 340. + * * @see NumberFormat#setMinimumFractionDigits * @stable ICU 2.0 */ @@ -5258,11 +5142,10 @@ public class DecimalFormat extends NumberFormat { } /** - * Sets whether {@link #parse(String, ParsePosition)} returns BigDecimal. The - * default value is false. - * - * @param value true if {@link #parse(String, ParsePosition)} - * returns BigDecimal. + * Sets whether {@link #parse(String, ParsePosition)} returns BigDecimal. The default value is false. + * + * @param value + * true if {@link #parse(String, ParsePosition)} returns BigDecimal. * @stable ICU 3.6 */ public void setParseBigDecimal(boolean value) { @@ -5271,33 +5154,34 @@ public class DecimalFormat extends NumberFormat { /** * Returns whether {@link #parse(String, ParsePosition)} returns BigDecimal. - * + * * @return true if {@link #parse(String, ParsePosition)} returns BigDecimal. * @stable ICU 3.6 */ public boolean isParseBigDecimal() { return parseBigDecimal; } - + /** - * Set the maximum number of exponent digits when parsing a number. - * If the limit is set too high, an OutOfMemoryException may be triggered. - * The default value is 1000. - * @param newValue the new limit - * @stable ICU 51 - */ + * Set the maximum number of exponent digits when parsing a number. If the limit is set too high, an + * OutOfMemoryException may be triggered. The default value is 1000. + * + * @param newValue + * the new limit + * @stable ICU 51 + */ public void setParseMaxDigits(int newValue) { if (newValue > 0) { PARSE_MAX_EXPONENT = newValue; } } - + /** - * Get the current maximum number of exponent digits when parsing a - * number. - * @return the maximum number of exponent digits for parsing - * @stable ICU 51 - */ + * Get the current maximum number of exponent digits when parsing a number. + * + * @return the maximum number of exponent digits for parsing + * @stable ICU 51 + */ public int getParseMaxDigits() { return PARSE_MAX_EXPONENT; } @@ -5315,12 +5199,10 @@ public class DecimalFormat extends NumberFormat { } /** - * First, read the default serializable fields from the stream. Then if - *serialVersionOnStream
is less than 1, indicating that the stream was - * written by JDK 1.1, initializeuseExponentialNotation
to false, since - * it was not present in JDK 1.1. Finally, set serialVersionOnStream back to the - * maximum allowed value so that default serialization will work properly if this - * object is streamed out again. + * First, read the default serializable fields from the stream. Then ifserialVersionOnStream
is less + * than 1, indicating that the stream was written by JDK 1.1, initializeuseExponentialNotation
to + * false, since it was not present in JDK 1.1. Finally, set serialVersionOnStream back to the maximum allowed value + * so that default serialization will work properly if this object is streamed out again. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); @@ -5335,7 +5217,6 @@ public class DecimalFormat extends NumberFormat { // getMaximumFractionDigits() > DOUBLE_FRACTION_DIGITS) { throw new // InvalidObjectException("Digit count out of range"); } - // Truncate the maximumIntegerDigits to DOUBLE_INTEGER_DIGITS and // maximumFractionDigits to DOUBLE_FRACTION_DIGITS @@ -5358,10 +5239,13 @@ public class DecimalFormat extends NumberFormat { } } if (serialVersionOnStream < 3) { - // Versions prior to 3 do not store a currency object. Create one to match + // Versions prior to 3 do not store a currency object. Create one to match // the DecimalFormatSymbols object. setCurrencyForSymbols(); } + if (serialVersionOnStream < 4) { + currencyUsage = CurrencyUsage.STANDARD; + } serialVersionOnStream = currentSerialVersion; digitList = new DigitList(); @@ -5369,6 +5253,7 @@ public class DecimalFormat extends NumberFormat { setInternalRoundingIncrement(new BigDecimal(roundingIncrement)); } resetActualRounding(); + } private void setInternalRoundingIncrement(BigDecimal value) { @@ -5384,16 +5269,15 @@ public class DecimalFormat extends NumberFormat { /** * The symbol used as a prefix when formatting positive numbers, e.g. "+". - * + * * @serial * @see #getPositivePrefix */ private String positivePrefix = ""; /** - * The symbol used as a suffix when formatting positive numbers. This is often an - * empty string. - * + * The symbol used as a suffix when formatting positive numbers. This is often an empty string. + * * @serial * @see #getPositiveSuffix */ @@ -5401,88 +5285,82 @@ public class DecimalFormat extends NumberFormat { /** * The symbol used as a prefix when formatting negative numbers, e.g. "-". - * + * * @serial * @see #getNegativePrefix */ private String negativePrefix = "-"; /** - * The symbol used as a suffix when formatting negative numbers. This is often an - * empty string. - * + * The symbol used as a suffix when formatting negative numbers. This is often an empty string. + * * @serial * @see #getNegativeSuffix */ private String negativeSuffix = ""; /** - * The prefix pattern for non-negative numbers. This variable corresponds to - *positivePrefix
. - * - *This pattern is expanded by the method
expandAffix()
to - *positivePrefix
to update the latter to reflect changes in - *symbols
. If this variable isnull
then - *positivePrefix
is taken as a literal value that does not change when - *symbols
changes. This variable is alwaysnull
for - *DecimalFormat
objects older than stream version 2 restored from - * stream. - * + * The prefix pattern for non-negative numbers. This variable corresponds topositivePrefix
. + * + *+ * This pattern is expanded by the method
expandAffix()
topositivePrefix
to update the + * latter to reflect changes insymbols
. If this variable isnull
then + *positivePrefix
is taken as a literal value that does not change whensymbols
changes. + * This variable is alwaysnull
forDecimalFormat
objects older than stream version 2 + * restored from stream. + * * @serial */ // [Richard/GCL] private String posPrefixPattern; /** - * The suffix pattern for non-negative numbers. This variable corresponds to - *positiveSuffix
. This variable is analogous to - *posPrefixPattern
; see that variable for further documentation. - * + * The suffix pattern for non-negative numbers. This variable corresponds topositiveSuffix
. This + * variable is analogous toposPrefixPattern
; see that variable for further documentation. + * * @serial */ // [Richard/GCL] private String posSuffixPattern; /** - * The prefix pattern for negative numbers. This variable corresponds to - *negativePrefix
. This variable is analogous to - *posPrefixPattern
; see that variable for further documentation. - * + * The prefix pattern for negative numbers. This variable corresponds tonegativePrefix
. This variable + * is analogous toposPrefixPattern
; see that variable for further documentation. + * * @serial */ // [Richard/GCL] private String negPrefixPattern; /** - * The suffix pattern for negative numbers. This variable corresponds to - *negativeSuffix
. This variable is analogous to - *posPrefixPattern
; see that variable for further documentation. - * + * The suffix pattern for negative numbers. This variable corresponds tonegativeSuffix
. This variable + * is analogous toposPrefixPattern
; see that variable for further documentation. + * * @serial */ // [Richard/GCL] private String negSuffixPattern; /** - * Formatter for ChoiceFormat-based currency names. If this field is not null, then - * delegate to it to format currency symbols. - * + * Formatter for ChoiceFormat-based currency names. If this field is not null, then delegate to it to format + * currency symbols. + * * @since ICU 2.6 */ private ChoiceFormat currencyChoice; /** * The multiplier for use in percent, permill, etc. - * + * * @serial * @see #getMultiplier */ private int multiplier = 1; /** - * The number of digits between grouping separators in the integer portion of a - * number. Must be greater than 0 ifNumberFormat.groupingUsed
is true. - * + * The number of digits between grouping separators in the integer portion of a number. Must be greater than 0 if + *NumberFormat.groupingUsed
is true. + * * @serial * @see #getGroupingSize * @see NumberFormat#isGroupingUsed @@ -5490,27 +5368,26 @@ public class DecimalFormat extends NumberFormat { private byte groupingSize = 3; // invariant, > 0 if useThousands /** - * The secondary grouping size. This is only used for Hindi numerals, which use a - * primary grouping of 3 and a secondary grouping of 2, e.g., "12,34,567". If this - * value is less than 1, then secondary grouping is equal to the primary grouping. - * + * The secondary grouping size. This is only used for Hindi numerals, which use a primary grouping of 3 and a + * secondary grouping of 2, e.g., "12,34,567". If this value is less than 1, then secondary grouping is equal to the + * primary grouping. + * */ private byte groupingSize2 = 0; /** - * If true, forces the decimal separator to always appear in a formatted number, even - * if the fractional part of the number is zero. - * + * If true, forces the decimal separator to always appear in a formatted number, even if the fractional part of the + * number is zero. + * * @serial * @see #isDecimalSeparatorAlwaysShown */ private boolean decimalSeparatorAlwaysShown = false; /** - * TheDecimalFormatSymbols
object used by this format. It contains the - * symbols used to format numbers, e.g. the grouping separator, decimal separator, and - * so on. - * + * TheDecimalFormatSymbols
object used by this format. It contains the symbols used to format numbers, + * e.g. the grouping separator, decimal separator, and so on. + * * @serial * @see #setDecimalFormatSymbols * @see DecimalFormatSymbols @@ -5519,72 +5396,68 @@ public class DecimalFormat extends NumberFormat { /** * True to use significant digits rather than integer and fraction digit counts. - * + * * @serial * @since ICU 3.0 */ private boolean useSignificantDigits = false; /** - * The minimum number of significant digits to show. Must be >= 1 and <= - * maxSignificantDigits. Ignored unless useSignificantDigits == true. - * + * The minimum number of significant digits to show. Must be >= 1 and <= maxSignificantDigits. Ignored unless + * useSignificantDigits == true. + * * @serial * @since ICU 3.0 */ private int minSignificantDigits = 1; /** - * The maximum number of significant digits to show. Must be >= - * minSignficantDigits. Ignored unless useSignificantDigits == true. - * + * The maximum number of significant digits to show. Must be >= minSignficantDigits. Ignored unless + * useSignificantDigits == true. + * * @serial * @since ICU 3.0 */ private int maxSignificantDigits = 6; /** - * True to force the use of exponential (i.e. scientific) notation - * when formatting numbers. - * - *Note that the JDK 1.2 public API provides no way to set this - * field, even though it is supported by the implementation and - * the stream format. The intent is that this will be added to the - * API in the future. - * + * True to force the use of exponential (i.e. scientific) notation when formatting numbers. + * + *
+ * Note that the JDK 1.2 public API provides no way to set this field, even though it is supported by the + * implementation and the stream format. The intent is that this will be added to the API in the future. + * * @serial */ private boolean useExponentialNotation; // Newly persistent in JDK 1.2 /** - * The minimum number of digits used to display the exponent when a number is - * formatted in exponential notation. This field is ignored if - *
useExponentialNotation
is not true. - * - *Note that the JDK 1.2 public API provides no way to set this field, even though - * it is supported by the implementation and the stream format. The intent is that - * this will be added to the API in the future. - * + * The minimum number of digits used to display the exponent when a number is formatted in exponential notation. + * This field is ignored if
useExponentialNotation
is not true. + * + *+ * Note that the JDK 1.2 public API provides no way to set this field, even though it is supported by the + * implementation and the stream format. The intent is that this will be added to the API in the future. + * * @serial */ private byte minExponentDigits; // Newly persistent in JDK 1.2 /** - * If true, the exponent is always prefixed with either the plus sign or the minus - * sign. Otherwise, only negative exponents are prefixed with the minus sign. This has - * no effect unless
useExponentialNotation
is true. - * + * If true, the exponent is always prefixed with either the plus sign or the minus sign. Otherwise, only negative + * exponents are prefixed with the minus sign. This has no effect unlessuseExponentialNotation
is + * true. + * * @serial * @since AlphaWorks NumberFormat */ private boolean exponentSignAlwaysShown = false; /** - * The value to which numbers are rounded during formatting. For example, if the - * rounding increment is 0.05, then 13.371 would be formatted as 13.350, assuming 3 - * fraction digits. Has the valuenull
if rounding is not in effect, or a - * positive value if rounding is in effect. Default valuenull
. - * + * The value to which numbers are rounded during formatting. For example, if the rounding increment is 0.05, then + * 13.371 would be formatted as 13.350, assuming 3 fraction digits. Has the valuenull
if rounding is + * not in effect, or a positive value if rounding is in effect. Default valuenull
. + * * @serial * @since AlphaWorks NumberFormat */ @@ -5593,74 +5466,66 @@ public class DecimalFormat extends NumberFormat { private java.math.BigDecimal roundingIncrement = null; /** - * The value to which numbers are rounded during formatting. For example, if the - * rounding increment is 0.05, then 13.371 would be formatted as 13.350, assuming 3 - * fraction digits. Has the valuenull
if rounding is not in effect, or a - * positive value if rounding is in effect. Default valuenull
. WARNING: - * the roundingIncrement value is the one serialized. - * + * The value to which numbers are rounded during formatting. For example, if the rounding increment is 0.05, then + * 13.371 would be formatted as 13.350, assuming 3 fraction digits. Has the valuenull
if rounding is + * not in effect, or a positive value if rounding is in effect. Default valuenull
. WARNING: the + * roundingIncrement value is the one serialized. + * * @serial * @since AlphaWorks NumberFormat */ private transient BigDecimal roundingIncrementICU = null; /** - * The rounding mode. This value controls any rounding operations which occur when - * applying a rounding increment or when reducing the number of fraction digits to - * satisfy a maximum fraction digits limit. The value may assume any of the - *BigDecimal
rounding mode values. Default value - *BigDecimal.ROUND_HALF_EVEN
. - * + * The rounding mode. This value controls any rounding operations which occur when applying a rounding increment or + * when reducing the number of fraction digits to satisfy a maximum fraction digits limit. The value may assume any + * of theBigDecimal
rounding mode values. Default valueBigDecimal.ROUND_HALF_EVEN
. + * * @serial * @since AlphaWorks NumberFormat */ private int roundingMode = BigDecimal.ROUND_HALF_EVEN; /** - * Operations onBigDecimal
numbers are controlled by a {@link - * MathContext} object, which provides the context (precision and other information) - * for the operation. The defaultMathContext
settings are - *digits=0, form=PLAIN, lostDigits=false, roundingMode=ROUND_HALF_UP
; - * these settings perform fixed point arithmetic with unlimited precision, as defined - * for the original BigDecimal class in Java 1.1 and Java 1.2 + * Operations onBigDecimal
numbers are controlled by a {@link MathContext} object, which provides the + * context (precision and other information) for the operation. The defaultMathContext
settings are + *digits=0, form=PLAIN, lostDigits=false, roundingMode=ROUND_HALF_UP
; these settings perform fixed + * point arithmetic with unlimited precision, as defined for the original BigDecimal class in Java 1.1 and Java 1.2 */ // context for plain unlimited math private MathContext mathContext = new MathContext(0, MathContext.PLAIN); /** - * The padded format width, or zero if there is no padding. Must be >= 0. Default - * value zero. - * + * The padded format width, or zero if there is no padding. Must be >= 0. Default value zero. + * * @serial * @since AlphaWorks NumberFormat */ private int formatWidth = 0; /** - * The character used to pad the result of format toformatWidth
, if - * padding is in effect. Default value ' '. - * + * The character used to pad the result of format toformatWidth
, if padding is in effect. Default + * value ' '. + * * @serial * @since AlphaWorks NumberFormat */ private char pad = ' '; /** - * The position in the string at which thepad
character will be - * inserted, if padding is in effect. Must have a value from - *PAD_BEFORE_PREFIX
toPAD_AFTER_SUFFIX
. Default value + * The position in the string at which thepad
character will be inserted, if padding is in effect. + * Must have a value fromPAD_BEFORE_PREFIX
toPAD_AFTER_SUFFIX
. Default value *PAD_BEFORE_PREFIX
. - * + * * @serial * @since AlphaWorks NumberFormat */ private int padPosition = PAD_BEFORE_PREFIX; /** - * True if {@link #parse(String, ParsePosition)} to return BigDecimal rather than - * Long, Double or BigDecimal except special values. This property is introduced for - * J2SE 5 compatibility support. - * + * True if {@link #parse(String, ParsePosition)} to return BigDecimal rather than Long, Double or BigDecimal except + * special values. This property is introduced for J2SE 5 compatibility support. + * * @serial * @since ICU 3.6 * @see #setParseBigDecimal(boolean) @@ -5668,28 +5533,36 @@ public class DecimalFormat extends NumberFormat { */ private boolean parseBigDecimal = false; + /** + * The currency usage for the NumberFormat(standard or cash usage). It is used as STANDARD by default + * + * @since ICU 54 + */ + private CurrencyUsage currencyUsage = CurrencyUsage.STANDARD; + // ---------------------------------------------------------------------- - static final int currentSerialVersion = 3; + static final int currentSerialVersion = 4; /** - * The internal serial version which says which version was written Possible values - * are: - * + * The internal serial version which says which version was written Possible values are: + * *- * + * *
- * + * * @serial */ private int serialVersionOnStream = currentSerialVersion; @@ -5699,9 +5572,9 @@ public class DecimalFormat extends NumberFormat { // ---------------------------------------------------------------------- /** - * {@icu} Constant for {@link #getPadPosition()} and {@link #setPadPosition(int)} to - * specify pad characters inserted before the prefix. - * + * {@icu} Constant for {@link #getPadPosition()} and {@link #setPadPosition(int)} to specify pad characters inserted + * before the prefix. + * * @see #setPadPosition * @see #getPadPosition * @see #PAD_AFTER_PREFIX @@ -5712,9 +5585,9 @@ public class DecimalFormat extends NumberFormat { public static final int PAD_BEFORE_PREFIX = 0; /** - * {@icu} Constant for {@link #getPadPosition()} and {@link #setPadPosition(int)} to - * specify pad characters inserted after the prefix. - * + * {@icu} Constant for {@link #getPadPosition()} and {@link #setPadPosition(int)} to specify pad characters inserted + * after the prefix. + * * @see #setPadPosition * @see #getPadPosition * @see #PAD_BEFORE_PREFIX @@ -5725,9 +5598,9 @@ public class DecimalFormat extends NumberFormat { public static final int PAD_AFTER_PREFIX = 1; /** - * {@icu} Constant for {@link #getPadPosition()} and {@link #setPadPosition(int)} to - * specify pad characters inserted before the suffix. - * + * {@icu} Constant for {@link #getPadPosition()} and {@link #setPadPosition(int)} to specify pad characters inserted + * before the suffix. + * * @see #setPadPosition * @see #getPadPosition * @see #PAD_BEFORE_PREFIX @@ -5738,9 +5611,9 @@ public class DecimalFormat extends NumberFormat { public static final int PAD_BEFORE_SUFFIX = 2; /** - * {@icu} Constant for {@link #getPadPosition()} and {@link #setPadPosition(int)} to - * specify pad characters inserted after the suffix. - * + * {@icu} Constant for {@link #getPadPosition()} and {@link #setPadPosition(int)} to specify pad characters inserted + * after the suffix. + * * @see #setPadPosition * @see #getPadPosition * @see #PAD_BEFORE_PREFIX @@ -5784,11 +5657,10 @@ public class DecimalFormat extends NumberFormat { // Also plus sign. Also exponent. /** - * The CURRENCY_SIGN is the standard Unicode symbol for currency. It is used in - * patterns and substitued with either the currency symbol, or if it is doubled, with - * the international currency symbol. If the CURRENCY_SIGN is seen in a pattern, then - * the decimal separator is replaced with the monetary decimal separator. - * + * The CURRENCY_SIGN is the standard Unicode symbol for currency. It is used in patterns and substitued with either + * the currency symbol, or if it is doubled, with the international currency symbol. If the CURRENCY_SIGN is seen in + * a pattern, then the decimal separator is replaced with the monetary decimal separator. + * * The CURRENCY_SIGN is not localized. */ private static final char CURRENCY_SIGN = '\u00A4'; @@ -5802,12 +5674,11 @@ public class DecimalFormat extends NumberFormat { static final int DOUBLE_FRACTION_DIGITS = 340; /** - * When someone turns on scientific mode, we assume that more than this number of - * digits is due to flipping from some other mode that didn't restrict the maximum, - * and so we force 1 integer digit. We don't bother to track and see if someone is - * using exponential notation with more than this number, it wouldn't make sense - * anyway, and this is just to make sure that someone turning on scientific mode with - * default settings doesn't end up with lots of zeroes. + * When someone turns on scientific mode, we assume that more than this number of digits is due to flipping from + * some other mode that didn't restrict the maximum, and so we force 1 integer digit. We don't bother to track and + * see if someone is using exponential notation with more than this number, it wouldn't make sense anyway, and this + * is just to make sure that someone turning on scientific mode with default settings doesn't end up with lots of + * zeroes. */ static final int MAX_SCIENTIFIC_INTEGER_DIGITS = 8; @@ -5825,10 +5696,10 @@ public class DecimalFormat extends NumberFormat { // // -- default currency plural pattern char array // private static final char[] defaultCurrencyPluralPatternChar = - // {0, '.', '#', '#', ' ', 0xA4, 0xA4, 0xA4}; + // {0, '.', '#', '#', ' ', 0xA4, 0xA4, 0xA4}; // -- default currency plural pattern string // private static final String defaultCurrencyPluralPattern = - // new String(defaultCurrencyPluralPatternChar); + // new String(defaultCurrencyPluralPatternChar); // pattern used in this formatter private String formatPattern = ""; @@ -5836,20 +5707,18 @@ public class DecimalFormat extends NumberFormat { // DecimalFormat(pattern, decimalFormatSymbol, style) private int style = NumberFormat.NUMBERSTYLE; /** - * Represents whether this is a currency format, and which currency format style. 0: - * not currency format type; 1: currency style -- symbol name, such as "$" for US - * dollar. 2: currency style -- ISO name, such as USD for US dollar. 3: currency style - * -- plural long name, such as "US Dollar" for "1.00 US Dollar", or "US Dollars" for + * Represents whether this is a currency format, and which currency format style. 0: not currency format type; 1: + * currency style -- symbol name, such as "$" for US dollar. 2: currency style -- ISO name, such as USD for US + * dollar. 3: currency style -- plural long name, such as "US Dollar" for "1.00 US Dollar", or "US Dollars" for * "3.00 US Dollars". */ private int currencySignCount = CURRENCY_SIGN_COUNT_ZERO; /** - * For parsing purposes, we need to remember all prefix patterns and suffix patterns - * of every currency format pattern, including the pattern of the default currency - * style, ISO currency style, and plural currency style. The patterns are set through - * applyPattern. The following are used to represent the affix patterns in currency - * plural formats. + * For parsing purposes, we need to remember all prefix patterns and suffix patterns of every currency format + * pattern, including the pattern of the default currency style, ISO currency style, and plural currency style. The + * patterns are set through applyPattern. The following are used to represent the affix patterns in currency plural + * formats. */ private static final class AffixForCurrency { // negative prefix pattern @@ -5862,8 +5731,7 @@ public class DecimalFormat extends NumberFormat { private String posSuffixPatternForCurrency = null; private final int patternType; - public AffixForCurrency(String negPrefix, String negSuffix, String posPrefix, - String posSuffix, int type) { + public AffixForCurrency(String negPrefix, String negSuffix, String posPrefix, String posSuffix, int type) { negPrefixPatternForCurrency = negPrefix; negSuffixPatternForCurrency = negSuffix; posPrefixPatternForCurrency = posPrefix; @@ -5892,7 +5760,7 @@ public class DecimalFormat extends NumberFormat { } } - // Affix pattern set for currency. It is a set of AffixForCurrency, each element of + // Affix pattern set for currency. It is a set of AffixForCurrency, each element of // the set saves the negative prefix, negative suffix, positive prefix, and positive // suffix of a pattern. private transient Set- 0 (default): versions before JDK 1.2 - * + * *
- 1: version from JDK 1.2 and later, which includes the two new fields *
useExponentialNotation
andminExponentDigits
. - * - *- 2: version on AlphaWorks, which adds roundingMode, formatWidth, pad, - * padPosition, exponentSignAlwaysShown, roundingIncrement. - * + * + *
- 2: version on AlphaWorks, which adds roundingMode, formatWidth, pad, padPosition, + * exponentSignAlwaysShown, roundingIncrement. + * *
- 3: ICU 2.2. Adds currency object. - * + * + *
- 4: ICU 54. Adds currency usage(standard vs cash) + * *
affixPatternsForCurrency = null; @@ -5905,11 +5773,10 @@ public class DecimalFormat extends NumberFormat { private CurrencyPluralInfo currencyPluralInfo = null; /** - * Unit is an immutable class for the textual representation of a unit, in - * particular its prefix and suffix. - * + * Unit is an immutable class for the textual representation of a unit, in particular its prefix and suffix. + * * @author rocketman - * + * */ static class Unit { private final String prefix; @@ -5939,6 +5806,7 @@ public class DecimalFormat extends NumberFormat { Unit other = (Unit) obj; return prefix.equals(other.prefix) && suffix.equals(other.suffix); } + @Override public String toString() { return prefix + "/" + suffix; @@ -5975,24 +5843,23 @@ public class DecimalFormat extends NumberFormat { private transient double roundingDouble = 0.0; /* - * If the roundingDouble is the reciprocal of an integer (the most common case!), this - * is set to be that integer. Otherwise it is 0.0. + * If the roundingDouble is the reciprocal of an integer (the most common case!), this is set to be that integer. + * Otherwise it is 0.0. */ private transient double roundingDoubleReciprocal = 0.0; /* - * Set roundingDouble, roundingDoubleReciprocal and actualRoundingIncrement - * based on rounding mode and width of fractional digits. Whenever setting affecting - * rounding mode, rounding increment and maximum width of fractional digits, then - * this method must be called. + * Set roundingDouble, roundingDoubleReciprocal and actualRoundingIncrement based on rounding mode and width of + * fractional digits. Whenever setting affecting rounding mode, rounding increment and maximum width of fractional + * digits, then this method must be called. * - * roundingIncrementICU is the field storing the custom rounding increment value, - * while actual rounding increment could be larger. + * roundingIncrementICU is the field storing the custom rounding increment value, while actual rounding increment + * could be larger. */ private void resetActualRounding() { if (roundingIncrementICU != null) { - BigDecimal byWidth = getMaximumFractionDigits() > 0 ? - BigDecimal.ONE.movePointLeft(getMaximumFractionDigits()) : BigDecimal.ONE; + BigDecimal byWidth = getMaximumFractionDigits() > 0 ? BigDecimal.ONE + .movePointLeft(getMaximumFractionDigits()) : BigDecimal.ONE; if (roundingIncrementICU.compareTo(byWidth) >= 0) { actualRoundingIncrementICU = roundingIncrementICU; } else { @@ -6001,13 +5868,13 @@ public class DecimalFormat extends NumberFormat { } else { if (roundingMode == BigDecimal.ROUND_HALF_EVEN || isScientificNotation()) { // This rounding fix is irrelevant if mode is ROUND_HALF_EVEN as DigitList - // does ROUND_HALF_EVEN for us. This rounding fix won't work at all for + // does ROUND_HALF_EVEN for us. This rounding fix won't work at all for // scientific notation. actualRoundingIncrementICU = null; } else { if (getMaximumFractionDigits() > 0) { actualRoundingIncrementICU = BigDecimal.ONE.movePointLeft(getMaximumFractionDigits()); - } else { + } else { actualRoundingIncrementICU = BigDecimal.ONE; } } diff --git a/icu4j/main/classes/core/src/com/ibm/icu/text/NumberFormat.java b/icu4j/main/classes/core/src/com/ibm/icu/text/NumberFormat.java index 088d07f308..0160029290 100644 --- a/icu4j/main/classes/core/src/com/ibm/icu/text/NumberFormat.java +++ b/icu4j/main/classes/core/src/com/ibm/icu/text/NumberFormat.java @@ -23,6 +23,7 @@ import java.util.Set; import com.ibm.icu.impl.ICUResourceBundle; import com.ibm.icu.util.Currency; +import com.ibm.icu.util.Currency.CurrencyUsage; import com.ibm.icu.util.CurrencyAmount; import com.ibm.icu.util.ULocale; import com.ibm.icu.util.ULocale.Category; @@ -30,221 +31,207 @@ import com.ibm.icu.util.UResourceBundle; /** * {@icuenhanced java.text.NumberFormat}.{@icu _usage_} - * - * NumberFormat
is the abstract base class for all number - * formats. This class provides the interface for formatting and parsing - * numbers.NumberFormat
also provides methods for determining - * which locales have number formats, and what their names are. - * - *NumberFormat
helps you to format and parse numbers for any locale. - * Your code can be completely independent of the locale conventions for - * decimal points, thousands-separators, or even the particular decimal - * digits used, or whether the number format is even decimal. - * + * + *NumberFormat
is the abstract base class for all number formats. This class provides the interface for + * formatting and parsing numbers.NumberFormat
also provides methods for determining which locales have + * number formats, and what their names are. + * + *NumberFormat
helps you to format and parse numbers for any locale. Your code can be completely + * independent of the locale conventions for decimal points, thousands-separators, or even the particular decimal digits + * used, or whether the number format is even decimal. + * *- * To format a number for the current Locale, use one of the factory - * class methods: - *
+ * To format a number for the current Locale, use one of the factory class methods:To format a number for a different Locale, specify it in the call to+ * *- * If you are formatting multiple numbers, it is - * more efficient to get the format and use it multiple times so that - * the system doesn't have to fetch the information about the local - * language and country conventions multiple times. - *- * myString = NumberFormat.getInstance().format(myNumber); + * myString = NumberFormat.getInstance().format(myNumber); *- *+ * + *If you are formatting multiple numbers, it is more efficient to get the format and use it multiple + * times so that the system doesn't have to fetch the information about the local language and country conventions + * multiple times.+ * *- * To format a number for a different Locale, specify it in the - * call to* NumberFormat nf = NumberFormat.getInstance(); - * for (int i = 0; i < a.length; ++i) { - * output.println(nf.format(myNumber[i]) + "; "); + * for (int i = 0; i < a.length; ++i) { + * output.println(nf.format(myNumber[i]) + "; "); * } *- *getInstance
. + * + *getInstance
. *+ * *- * You can also use a* NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH); *- *NumberFormat
to parse numbers: - *+ * + *You can also use aNumberFormat
to parse numbers:+ * *- * Use* myNumber = nf.parse(myString); *- *getInstance
orgetNumberInstance
to get the - * normal number format. UsegetIntegerInstance
to get an - * integer number format. UsegetCurrencyInstance
to get the - * currency number format. And usegetPercentInstance
to get a - * format for displaying percentages. Some factory methods are found within - * subclasses of NumberFormat. With this format, a fraction like - * 0.53 is displayed as 53%. - * + * + * UsegetInstance
orgetNumberInstance
to get the normal number format. Use + *getIntegerInstance
to get an integer number format. UsegetCurrencyInstance
to get the + * currency number format. And usegetPercentInstance
to get a format for displaying percentages. Some + * factory methods are found within subclasses of NumberFormat. With this format, a fraction like 0.53 is displayed as + * 53%. + * *- * Starting from ICU 4.2, you can use getInstance() by passing in a 'style' - * as parameter to get the correct instance. - * For example, - * use getInstance(...NUMBERSTYLE) to get the normal number format, - * getInstance(...PERCENTSTYLE) to get a format for displaying percentage, - * getInstance(...SCIENTIFICSTYLE) to get a format for displaying scientific number, - * getInstance(...INTEGERSTYLE) to get an integer number format, - * getInstance(...CURRENCYSTYLE) to get the currency number format, - * in which the currency is represented by its symbol, for example, "$3.00". - * getInstance(...ISOCURRENCYSTYLE) to get the currency number format, - * in which the currency is represented by its ISO code, for example "USD3.00". - * getInstance(...PLURALCURRENCYSTYLE) to get the currency number format, - * in which the currency is represented by its full name in plural format, - * for example, "3.00 US dollars" or "1.00 US dollar". - * - * + * Starting from ICU 4.2, you can use getInstance() by passing in a 'style' as parameter to get the correct instance. + * For example, use getInstance(...NUMBERSTYLE) to get the normal number format, getInstance(...PERCENTSTYLE) to get a + * format for displaying percentage, getInstance(...SCIENTIFICSTYLE) to get a format for displaying scientific number, + * getInstance(...INTEGERSTYLE) to get an integer number format, getInstance(...CURRENCYSTYLE) to get the currency + * number format, in which the currency is represented by its symbol, for example, "$3.00". + * getInstance(...ISOCURRENCYSTYLE) to get the currency number format, in which the currency is represented by its ISO + * code, for example "USD3.00". getInstance(...PLURALCURRENCYSTYLE) to get the currency number format, in which the + * currency is represented by its full name in plural format, for example, "3.00 US dollars" or "1.00 US dollar". + * + * *
- * You can also control the display of numbers with such methods as - *
setMinimumFractionDigits
. - * If you want even more control over the format or parsing, - * or want to give your users more control, - * you can try casting theNumberFormat
you get from the factory methods - * to aDecimalFormat
. This will work for the vast majority - * of locales; just remember to put it in atry
block in case you - * encounter an unusual one. - * + * You can also control the display of numbers with such methods assetMinimumFractionDigits
. If you want + * even more control over the format or parsing, or want to give your users more control, you can try casting the + *NumberFormat
you get from the factory methods to aDecimalFormat
. This will work for the + * vast majority of locales; just remember to put it in atry
block in case you encounter an unusual one. + * *- * NumberFormat is designed such that some controls - * work for formatting and others work for parsing. The following is + * NumberFormat is designed such that some controls work for formatting and others work for parsing. The following is * the detailed description for each these control methods, *
- * setParseIntegerOnly : only affects parsing, e.g. - * if true, "3456.78" -> 3456 (and leaves the parse position just after '6') - * if false, "3456.78" -> 3456.78 (and leaves the parse position just after '8') - * This is independent of formatting. If you want to not show a decimal point - * where there might be no digits after the decimal point, use + * setParseIntegerOnly : only affects parsing, e.g. if true, "3456.78" -> 3456 (and leaves the parse position just after + * '6') if false, "3456.78" -> 3456.78 (and leaves the parse position just after '8') This is independent of formatting. + * If you want to not show a decimal point where there might be no digits after the decimal point, use * setDecimalSeparatorAlwaysShown on DecimalFormat. *
- * You can also use forms of the
parse
andformat
- * methods withParsePosition
andFieldPosition
to - * allow you to: + * You can also use forms of theparse
andformat
methods withParsePosition
and + *FieldPosition
to allow you to: *- *
* For example, you can align numbers in two ways: *- progressively parse through pieces of a string - *
- align the decimal point and other areas + *
- progressively parse through pieces of a string + *
- align the decimal point and other areas *
- *
- * + * *- If you are using a monospaced font with spacing for alignment, - * you can pass the
FieldPosition
in your format call, with - *field
=INTEGER_FIELD
. On output, - *getEndIndex
will be set to the offset between the - * last character of the integer and the decimal. Add - * (desiredSpaceCount - getEndIndex) spaces at the front of the string. - * - *- If you are using proportional fonts, - * instead of padding with spaces, measure the width - * of the string in pixels from the start to
getEndIndex
. - * Then move the pen by - * (desiredPixelWidth - widthToAlignmentPoint) before drawing the text. - * It also works where there is no decimal, but possibly additional - * characters at the end, e.g., with parentheses in negative - * numbers: "(12)" for -12. + *- If you are using a monospaced font with spacing for alignment, you can pass the
FieldPosition
in + * your format call, withfield
=INTEGER_FIELD
. On output,getEndIndex
will be + * set to the offset between the last character of the integer and the decimal. Add (desiredSpaceCount - getEndIndex) + * spaces at the front of the string. + * + *- If you are using proportional fonts, instead of padding with spaces, measure the width of the string in pixels + * from the start to
getEndIndex
. Then move the pen by (desiredPixelWidth - widthToAlignmentPoint) before + * drawing the text. It also works where there is no decimal, but possibly additional characters at the end, e.g., with + * parentheses in negative numbers: "(12)" for -12. *Synchronization
*- * Number 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. + * Number 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. *
- * + * *
DecimalFormat
- *DecimalFormat is the concrete implementation of NumberFormat, and the - * NumberFormat API is essentially an abstraction from DecimalFormat's API. - * Refer to DecimalFormat for more information about this API.
- * - * see DecimalFormat - * see java.text.ChoiceFormat - * @author Mark Davis - * @author Helena Shih - * @author Alan Liu + *+ * DecimalFormat is the concrete implementation of NumberFormat, and the NumberFormat API is essentially an abstraction + * from DecimalFormat's API. Refer to DecimalFormat for more information about this API. + *
+ * + * see DecimalFormat see java.text.ChoiceFormat + * + * @author Mark Davis + * @author Helena Shih + * @author Alan Liu * @stable ICU 2.0 */ public abstract class NumberFormat extends UFormat { /** * {@icu} Constant to specify normal number style of format. + * * @stable ICU 4.2 */ public static final int NUMBERSTYLE = 0; /** - * {@icu} Constant to specify currency style of format which uses currency symbol - * to represent currency, for example: "$3.00". + * {@icu} Constant to specify currency style of format which uses currency symbol to represent currency, for + * example: "$3.00". + * * @stable ICU 4.2 */ public static final int CURRENCYSTYLE = 1; /** * {@icu} Constant to specify a style of format to display percent. + * * @stable ICU 4.2 */ public static final int PERCENTSTYLE = 2; /** * {@icu} Constant to specify a style of format to display scientific number. + * * @stable ICU 4.2 */ public static final int SCIENTIFICSTYLE = 3; /** * {@icu} Constant to specify a integer number style format. + * * @stable ICU 4.2 */ public static final int INTEGERSTYLE = 4; /** - * {@icu} Constant to specify currency style of format which uses currency - * ISO code to represent currency, for example: "USD3.00". + * {@icu} Constant to specify currency style of format which uses currency ISO code to represent currency, for + * example: "USD3.00". + * * @stable ICU 4.2 */ public static final int ISOCURRENCYSTYLE = 5; /** - * {@icu} Constant to specify currency style of format which uses currency - * long name with plural format to represent currency, for example, - * "3.00 US Dollars". + * {@icu} Constant to specify currency style of format which uses currency long name with plural format to represent + * currency, for example, "3.00 US Dollars". + * * @stable ICU 4.2 */ public static final int PLURALCURRENCYSTYLE = 6; /** - * {@icu} Constant to specify currency style of format which uses currency symbol - * to represent currency for accounting, for example: "($3.00), instead of - * "-$3.00" ({@link #CURRENCYSTYLE}). + * {@icu} Constant to specify currency style of format which uses currency symbol to represent currency for + * accounting, for example: "($3.00), instead of "-$3.00" ({@link #CURRENCYSTYLE}). + * * @draft ICU 53 * @provisional This API might change or be removed in a future release. */ public static final int ACCOUNTINGCURRENCYSTYLE = 7; - /** - * Field constant used to construct a FieldPosition object. Signifies that - * the position of the integer part of a formatted number should be returned. + * {@icu} Constant to specify currency cash style of format which uses currency ISO code to represent currency, for + * example: "NT$3" instead of "NT$3.23". + * + * @draft ICU 54 + */ + public static final int CASHCURRENCYSTYLE = 8; + /** + * /** Field constant used to construct a FieldPosition object. Signifies that the position of the integer part of a + * formatted number should be returned. + * * @see java.text.FieldPosition * @stable ICU 2.0 */ public static final int INTEGER_FIELD = 0; /** - * Field constant used to construct a FieldPosition object. Signifies that - * the position of the fraction part of a formatted number should be returned. + * Field constant used to construct a FieldPosition object. Signifies that the position of the fraction part of a + * formatted number should be returned. + * * @see java.text.FieldPosition * @stable ICU 2.0 */ public static final int FRACTION_FIELD = 1; /** - * Formats a number and appends the resulting text to the given string buffer. - * {@icunote} recognizesBigInteger
- * andBigDecimal
objects. + * Formats a number and appends the resulting text to the given string buffer. {@icunote} recognizes + *BigInteger
andBigDecimal
objects. + * * @see java.text.Format#format(Object, StringBuffer, FieldPosition) * @stable ICU 2.0 */ @Override - public StringBuffer format(Object number, - StringBuffer toAppendTo, - FieldPosition pos) { + public StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition pos) { if (number instanceof Long) { - return format(((Long)number).longValue(), toAppendTo, pos); + return format(((Long) number).longValue(), toAppendTo, pos); } else if (number instanceof BigInteger) { return format((BigInteger) number, toAppendTo, pos); } else if (number instanceof java.math.BigDecimal) { @@ -252,9 +239,9 @@ public abstract class NumberFormat extends UFormat { } else if (number instanceof com.ibm.icu.math.BigDecimal) { return format((com.ibm.icu.math.BigDecimal) number, toAppendTo, pos); } else if (number instanceof CurrencyAmount) { - return format((CurrencyAmount)number, toAppendTo, pos); + return format((CurrencyAmount) number, toAppendTo, pos); } else if (number instanceof Number) { - return format(((Number)number).doubleValue(), toAppendTo, pos); + return format(((Number) number).doubleValue(), toAppendTo, pos); } else { throw new IllegalArgumentException("Cannot format given Object as a Number"); } @@ -262,30 +249,33 @@ public abstract class NumberFormat extends UFormat { /** * Parses text from a string to produce a number. - * @param source the String to parse - * @param parsePosition the position at which to start the parse + * + * @param source + * the String to parse + * @param parsePosition + * the position at which to start the parse * @return the parsed number, or null * @see java.text.NumberFormat#parseObject(String, ParsePosition) * @stable ICU 2.0 */ @Override - public final Object parseObject(String source, - ParsePosition parsePosition) { + public final Object parseObject(String source, ParsePosition parsePosition) { return parse(source, parsePosition); } /** * Specialization of format. + * * @see java.text.Format#format(Object) * @stable ICU 2.0 */ public final String format(double number) { - return format(number,new StringBuffer(), - new FieldPosition(0)).toString(); + return format(number, new StringBuffer(), new FieldPosition(0)).toString(); } /** * Specialization of format. + * * @see java.text.Format#format(Object) * @stable ICU 2.0 */ @@ -298,106 +288,104 @@ public abstract class NumberFormat extends UFormat { /** * {@icu} Convenience method to format a BigInteger. + * * @stable ICU 2.0 */ public final String format(BigInteger number) { - return format(number, new StringBuffer(), - new FieldPosition(0)).toString(); + return format(number, new StringBuffer(), new FieldPosition(0)).toString(); } /** * Convenience method to format a BigDecimal. + * * @stable ICU 2.0 */ public final String format(java.math.BigDecimal number) { - return format(number, new StringBuffer(), - new FieldPosition(0)).toString(); + return format(number, new StringBuffer(), new FieldPosition(0)).toString(); } /** * {@icu} Convenience method to format an ICU BigDecimal. + * * @stable ICU 2.0 */ public final String format(com.ibm.icu.math.BigDecimal number) { - return format(number, new StringBuffer(), - new FieldPosition(0)).toString(); + return format(number, new StringBuffer(), new FieldPosition(0)).toString(); } /** * {@icu} Convenience method to format a CurrencyAmount. + * * @stable ICU 3.0 */ public final String format(CurrencyAmount currAmt) { - return format(currAmt, new StringBuffer(), - new FieldPosition(0)).toString(); + return format(currAmt, new StringBuffer(), new FieldPosition(0)).toString(); } /** * Specialization of format. + * * @see java.text.Format#format(Object, StringBuffer, FieldPosition) * @stable ICU 2.0 */ - public abstract StringBuffer format(double number, - StringBuffer toAppendTo, - FieldPosition pos); + public abstract StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos); /** * Specialization of format. + * * @see java.text.Format#format(Object, StringBuffer, FieldPosition) * @stable ICU 2.0 */ - public abstract StringBuffer format(long number, - StringBuffer toAppendTo, - FieldPosition pos); + public abstract StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos); + /** * {@icu} Formats a BigInteger. Specialization of format. + * * @see java.text.Format#format(Object, StringBuffer, FieldPosition) * @stable ICU 2.0 */ - public abstract StringBuffer format(BigInteger number, - StringBuffer toAppendTo, - FieldPosition pos); + public abstract StringBuffer format(BigInteger number, StringBuffer toAppendTo, FieldPosition pos); + /** * {@icu} Formats a BigDecimal. Specialization of format. + * * @see java.text.Format#format(Object, StringBuffer, FieldPosition) * @stable ICU 2.0 */ - public abstract StringBuffer format(java.math.BigDecimal number, - StringBuffer toAppendTo, - FieldPosition pos); + public abstract StringBuffer format(java.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos); + /** * {@icu} Formats an ICU BigDecimal. Specialization of format. + * * @see java.text.Format#format(Object, StringBuffer, FieldPosition) * @stable ICU 2.0 */ - public abstract StringBuffer format(com.ibm.icu.math.BigDecimal number, - StringBuffer toAppendTo, - FieldPosition pos); + public abstract StringBuffer format(com.ibm.icu.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos); + /** * {@icu} Formats a CurrencyAmount. Specialization of format. + * * @see java.text.Format#format(Object, StringBuffer, FieldPosition) * @stable ICU 3.0 */ - public StringBuffer format(CurrencyAmount currAmt, - StringBuffer toAppendTo, - FieldPosition pos) { + public StringBuffer format(CurrencyAmount currAmt, StringBuffer toAppendTo, FieldPosition pos) { // Default implementation -- subclasses may override Currency save = getCurrency(), curr = currAmt.getCurrency(); boolean same = curr.equals(save); - if (!same) setCurrency(curr); + if (!same) + setCurrency(curr); format(currAmt.getNumber(), toAppendTo, pos); - if (!same) setCurrency(save); + if (!same) + setCurrency(save); return toAppendTo; } /** - * Returns a Long if possible (e.g., within the range [Long.MIN_VALUE, - * Long.MAX_VALUE] and with no decimals), otherwise a Double. - * If IntegerOnly is set, will stop at a decimal - * point (or equivalent; e.g., for rational numbers "1 2/3", will stop - * after the 1). - * Does not throw an exception; if no object can be parsed, index is + * Returns a Long if possible (e.g., within the range [Long.MIN_VALUE, Long.MAX_VALUE] and with no decimals), + * otherwise a Double. If IntegerOnly is set, will stop at a decimal point (or equivalent; e.g., for rational + * numbers "1 2/3", will stop after the 1). Does not throw an exception; if no object can be parsed, index is * unchanged! + * * @see #isParseIntegerOnly * @see java.text.Format#parseObject(String, ParsePosition) * @stable ICU 2.0 @@ -405,59 +393,56 @@ public abstract class NumberFormat extends UFormat { public abstract Number parse(String text, ParsePosition parsePosition); /** - * Parses text from the beginning of the given string to produce a number. - * The method might not use the entire text of the given string. - * - * @param text A String whose beginning should be parsed. + * Parses text from the beginning of the given string to produce a number. The method might not use the entire text + * of the given string. + * + * @param text + * A String whose beginning should be parsed. * @return A Number parsed from the string. - * @throws ParseException if the beginning of the specified string - * cannot be parsed. + * @throws ParseException + * if the beginning of the specified string cannot be parsed. * @see #format * @stable ICU 2.0 */ - //Bug 4375399 [Richard/GCL] + // Bug 4375399 [Richard/GCL] public Number parse(String text) throws ParseException { ParsePosition parsePosition = new ParsePosition(0); Number result = parse(text, parsePosition); if (parsePosition.getIndex() == 0) { - throw new ParseException("Unparseable number: \"" + text + '"', - parsePosition.getErrorIndex()); + throw new ParseException("Unparseable number: \"" + text + '"', parsePosition.getErrorIndex()); } return result; } /** - * Parses text from the given string as a CurrencyAmount. Unlike - * the parse() method, this method will attempt to parse a generic - * currency name, searching for a match of this object's locale's - * currency display names, or for a 3-letter ISO currency code. - * This method will fail if this format is not a currency format, - * that is, if it does not contain the currency pattern symbol - * (U+00A4) in its prefix or suffix. - * - * @param text the text to parse - * @param pos input-output position; on input, the position within - * text to match; must have 0 <= pos.getIndex() < text.length(); - * on output, the position after the last matched character. If - * the parse fails, the position in unchanged upon output. + * Parses text from the given string as a CurrencyAmount. Unlike the parse() method, this method will attempt to + * parse a generic currency name, searching for a match of this object's locale's currency display names, or for a + * 3-letter ISO currency code. This method will fail if this format is not a currency format, that is, if it does + * not contain the currency pattern symbol (U+00A4) in its prefix or suffix. + * + * @param text + * the text to parse + * @param pos + * input-output position; on input, the position within text to match; must have 0 <= pos.getIndex() < + * text.length(); on output, the position after the last matched character. If the parse fails, the + * position in unchanged upon output. * @return a CurrencyAmount, or null upon failure * @stable ICU 49 */ public CurrencyAmount parseCurrency(CharSequence text, ParsePosition pos) { - ///CLOVER:OFF + // /CLOVER:OFF // Default implementation only -- subclasses should override Number n = parse(text.toString(), pos); return n == null ? null : new CurrencyAmount(n, getEffectiveCurrency()); - ///CLOVER:ON + // /CLOVER:ON } /** - * Returns true if this format will parse numbers as integers only. - * For example in the English locale, with ParseIntegerOnly true, the - * string "1234." would be parsed as the integer value 1234 and parsing - * would stop at the "." character. The decimal separator accepted - * by the parse operation is locale-dependent and determined by the + * Returns true if this format will parse numbers as integers only. For example in the English locale, with + * ParseIntegerOnly true, the string "1234." would be parsed as the integer value 1234 and parsing would stop at the + * "." character. The decimal separator accepted by the parse operation is locale-dependent and determined by the * subclass. + * * @return true if this will parse integers only * @stable ICU 2.0 */ @@ -467,7 +452,9 @@ public abstract class NumberFormat extends UFormat { /** * Sets whether or not numbers should be parsed as integers only. - * @param value true if this should parse integers only + * + * @param value + * true if this should parse integers only * @see #isParseIntegerOnly * @stable ICU 2.0 */ @@ -476,19 +463,20 @@ public abstract class NumberFormat extends UFormat { } /** - * {@icu} Sets whether strict parsing is in effect. When this is true, the - * following conditions cause a parse failure (examples use the pattern "#,##0.#"):+ * {@icu} Sets whether strict parsing is in effect. When this is true, the following conditions cause a parse + * failure (examples use the pattern "#,##0.#"): + *
*
- * When strict parsing is off, all grouping separators are ignored. - * This is the default behavior. - * @param value True to enable strict parsing. Default is false. + * When strict parsing is off, all grouping separators are ignored. This is the default behavior. + * + * @param value + * True to enable strict parsing. Default is false. * @see #isParseStrict * @stable ICU 3.6 */ @@ -498,6 +486,7 @@ public abstract class NumberFormat extends UFormat { /** * {@icu} Returns whether strict parsing is in effect. + * * @return true if strict parsing is in effect * @see #setParseStrict * @stable ICU 3.6 @@ -507,10 +496,10 @@ public abstract class NumberFormat extends UFormat { } /** - * {@icu} Set a particular DisplayContext value in the formatter, - * such as CAPITALIZATION_FOR_STANDALONE. + * {@icu} Set a particular DisplayContext value in the formatter, such as CAPITALIZATION_FOR_STANDALONE. * - * @param context The DisplayContext value to set. + * @param context + * The DisplayContext value to set. * @draft ICU 53 * @provisional This API might change or be removed in a future release. */ @@ -521,40 +510,39 @@ public abstract class NumberFormat extends UFormat { } /** - * {@icu} Get the formatter's DisplayContext value for the specified DisplayContext.Type, - * such as CAPITALIZATION. + * {@icu} Get the formatter's DisplayContext value for the specified DisplayContext.Type, such as CAPITALIZATION. * - * @param type the DisplayContext.Type whose value to return + * @param type + * the DisplayContext.Type whose value to return * @return the current DisplayContext setting for the specified type * @draft ICU 53 * @provisional This API might change or be removed in a future release. */ public DisplayContext getContext(DisplayContext.Type type) { - return (type == DisplayContext.Type.CAPITALIZATION && capitalizationSetting != null)? - capitalizationSetting: DisplayContext.CAPITALIZATION_NONE; + return (type == DisplayContext.Type.CAPITALIZATION && capitalizationSetting != null) ? capitalizationSetting + : DisplayContext.CAPITALIZATION_NONE; } - //============== Locale Stuff ===================== + // ============== Locale Stuff ===================== /** - * Returns the default number format for the current default- Leading or doubled grouping separators
*
* ',123' and '1,,234" fail- Groups of incorrect length when grouping is used
*
* '1,23' and '1234,567' fail, but '1234' passes- Grouping separators used in numbers followed by exponents
+ * '1,234E5' fails, but '1234E5' and '1,234E' pass ('E' is not an exponent when not followed by a number) *
- * '1,234E5' fails, but '1234E5' and '1,234E' pass ('E' is not an exponent when - * not followed by a number)FORMAT
locale. - * The default format is one of the styles provided by the other - * factory methods: getNumberInstance, getIntegerInstance, - * getCurrencyInstance or getPercentInstance. - * Exactly which one is locale-dependent. + * Returns the default number format for the current defaultFORMAT
locale. The default format is one + * of the styles provided by the other factory methods: getNumberInstance, getIntegerInstance, getCurrencyInstance + * or getPercentInstance. Exactly which one is locale-dependent. + * * @see Category#FORMAT * @stable ICU 2.0 */ - //Bug 4408066 [Richard/GCL] + // Bug 4408066 [Richard/GCL] public final static NumberFormat getInstance() { return getInstance(ULocale.getDefault(Category.FORMAT), NUMBERSTYLE); } /** - * Returns the default number format for the specified locale. - * The default format is one of the styles provided by the other - * factory methods: getNumberInstance, getCurrencyInstance or getPercentInstance. - * Exactly which one is locale-dependent. + * Returns the default number format for the specified locale. The default format is one of the styles provided by + * the other factory methods: getNumberInstance, getCurrencyInstance or getPercentInstance. Exactly which one is + * locale-dependent. + * * @stable ICU 2.0 */ public static NumberFormat getInstance(Locale inLocale) { @@ -562,10 +550,10 @@ public abstract class NumberFormat extends UFormat { } /** - * {@icu} Returns the default number format for the specified locale. - * The default format is one of the styles provided by the other - * factory methods: getNumberInstance, getCurrencyInstance or getPercentInstance. - * Exactly which one is locale-dependent. + * {@icu} Returns the default number format for the specified locale. The default format is one of the styles + * provided by the other factory methods: getNumberInstance, getCurrencyInstance or getPercentInstance. Exactly + * which one is locale-dependent. + * * @stable ICU 3.2 */ public static NumberFormat getInstance(ULocale inLocale) { @@ -574,7 +562,9 @@ public abstract class NumberFormat extends UFormat { /** * {@icu} Returns a specific style number format for defaultFORMAT
locale. - * @param style number format style + * + * @param style + * number format style * @see Category#FORMAT * @stable ICU 4.2 */ @@ -584,17 +574,20 @@ public abstract class NumberFormat extends UFormat { /** * {@icu} Returns a specific style number format for a specific locale. - * @param inLocale the specific locale. - * @param style number format style + * + * @param inLocale + * the specific locale. + * @param style + * number format style * @stable ICU 4.2 */ public static NumberFormat getInstance(Locale inLocale, int style) { return getInstance(ULocale.forLocale(inLocale), style); } - /** * Returns a general-purpose number format for the current defaultFORMAT
locale. + * * @see Category#FORMAT * @stable ICU 2.0 */ @@ -604,6 +597,7 @@ public abstract class NumberFormat extends UFormat { /** * Returns a general-purpose number format for the specified locale. + * * @stable ICU 2.0 */ public static NumberFormat getNumberInstance(Locale inLocale) { @@ -612,6 +606,7 @@ public abstract class NumberFormat extends UFormat { /** * {@icu} Returns a general-purpose number format for the specified locale. + * * @stable ICU 3.2 */ public static NumberFormat getNumberInstance(ULocale inLocale) { @@ -619,48 +614,44 @@ public abstract class NumberFormat extends UFormat { } /** - * Returns an integer number format for the current defaultFORMAT
locale. The - * returned number format is configured to round floating point numbers - * to the nearest integer using IEEE half-even rounding (see {@link - * com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting, - * and to parse only the integer part of an input string (see {@link - * #isParseIntegerOnly isParseIntegerOnly}). - * + * Returns an integer number format for the current defaultFORMAT
locale. The returned number format + * is configured to round floating point numbers to the nearest integer using IEEE half-even rounding (see + * {@link com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting, and to parse only the + * integer part of an input string (see {@link #isParseIntegerOnly isParseIntegerOnly}). + * * @return a number format for integer values * @see Category#FORMAT * @stable ICU 2.0 */ - //Bug 4408066 [Richard/GCL] + // Bug 4408066 [Richard/GCL] public final static NumberFormat getIntegerInstance() { return getInstance(ULocale.getDefault(Category.FORMAT), INTEGERSTYLE); } /** - * Returns an integer number format for the specified locale. The - * returned number format is configured to round floating point numbers - * to the nearest integer using IEEE half-even rounding (see {@link - * com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting, - * and to parse only the integer part of an input string (see {@link - * #isParseIntegerOnly isParseIntegerOnly}). - * - * @param inLocale the locale for which a number format is needed + * Returns an integer number format for the specified locale. The returned number format is configured to round + * floating point numbers to the nearest integer using IEEE half-even rounding (see + * {@link com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting, and to parse only the + * integer part of an input string (see {@link #isParseIntegerOnly isParseIntegerOnly}). + * + * @param inLocale + * the locale for which a number format is needed * @return a number format for integer values * @stable ICU 2.0 */ - //Bug 4408066 [Richard/GCL] + // Bug 4408066 [Richard/GCL] public static NumberFormat getIntegerInstance(Locale inLocale) { return getInstance(ULocale.forLocale(inLocale), INTEGERSTYLE); } /** - * {@icu} Returns an integer number format for the specified locale. The - * returned number format is configured to round floating point numbers - * to the nearest integer using IEEE half-even rounding (see {@link - * com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting, - * and to parse only the integer part of an input string (see {@link - * #isParseIntegerOnly isParseIntegerOnly}). - * - * @param inLocale the locale for which a number format is needed + * {@icu} Returns an integer number format for the specified locale. The returned number format is configured to + * round floating point numbers to the nearest integer using IEEE half-even rounding (see + * {@link com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting, and to parse only the + * integer part of an input string (see {@link #isParseIntegerOnly isParseIntegerOnly}). + * + * @param inLocale + * the locale for which a number format is needed * @return a number format for integer values * @stable ICU 3.2 */ @@ -670,6 +661,7 @@ public abstract class NumberFormat extends UFormat { /** * Returns a currency format for the current defaultFORMAT
locale. + * * @return a number format for currency * @see Category#FORMAT * @stable ICU 2.0 @@ -680,6 +672,7 @@ public abstract class NumberFormat extends UFormat { /** * Returns a currency format for the specified locale. + * * @return a number format for currency * @stable ICU 2.0 */ @@ -689,6 +682,7 @@ public abstract class NumberFormat extends UFormat { /** * {@icu} Returns a currency format for the specified locale. + * * @return a number format for currency * @stable ICU 3.2 */ @@ -698,6 +692,7 @@ public abstract class NumberFormat extends UFormat { /** * Returns a percentage format for the current defaultFORMAT
locale. + * * @return a number format for percents * @see Category#FORMAT * @stable ICU 2.0 @@ -708,6 +703,7 @@ public abstract class NumberFormat extends UFormat { /** * Returns a percentage format for the specified locale. + * * @return a number format for percents * @stable ICU 2.0 */ @@ -717,6 +713,7 @@ public abstract class NumberFormat extends UFormat { /** * {@icu} Returns a percentage format for the specified locale. + * * @return a number format for percents * @stable ICU 3.2 */ @@ -726,6 +723,7 @@ public abstract class NumberFormat extends UFormat { /** * {@icu} Returns a scientific format for the current defaultFORMAT
locale. + * * @return a scientific number format * @see Category#FORMAT * @stable ICU 2.0 @@ -736,6 +734,7 @@ public abstract class NumberFormat extends UFormat { /** * {@icu} Returns a scientific format for the specified locale. + * * @return a scientific number format * @stable ICU 2.0 */ @@ -745,6 +744,7 @@ public abstract class NumberFormat extends UFormat { /** * {@icu} Returns a scientific format for the specified locale. + * * @return a scientific number format * @stable ICU 3.2 */ @@ -754,54 +754,57 @@ public abstract class NumberFormat extends UFormat { // ===== Factory stuff ===== /** - * A NumberFormatFactory is used to register new number formats. The factory - * should be able to create any of the predefined formats for each locale it - * supports. When registered, the locales it supports extend or override the + * A NumberFormatFactory is used to register new number formats. The factory should be able to create any of the + * predefined formats for each locale it supports. When registered, the locales it supports extend or override the * locales already supported by ICU. - * - *Note: as of ICU4J 3.2, the default API for NumberFormatFactory uses - * ULocale instead of Locale. Instead of overriding createFormat(Locale, int), - * new implementations should override createFactory(ULocale, int). Note that - * one of these two methods MUST be overridden or else an infinite - * loop will occur. - * + * + *
+ * Note: as of ICU4J 3.2, the default API for NumberFormatFactory uses ULocale instead of Locale. Instead of + * overriding createFormat(Locale, int), new implementations should override createFactory(ULocale, int). Note that + * one of these two methods MUST be overridden or else an infinite loop will occur. + * * @stable ICU 2.6 */ public static abstract class NumberFormatFactory { /** * Value passed to format requesting a default number format. + * * @stable ICU 2.6 */ public static final int FORMAT_NUMBER = NUMBERSTYLE; /** * Value passed to format requesting a currency format. + * * @stable ICU 2.6 */ public static final int FORMAT_CURRENCY = CURRENCYSTYLE; /** * Value passed to format requesting a percent format. + * * @stable ICU 2.6 */ public static final int FORMAT_PERCENT = PERCENTSTYLE; /** * Value passed to format requesting a scientific format. + * * @stable ICU 2.6 */ public static final int FORMAT_SCIENTIFIC = SCIENTIFICSTYLE; /** * Value passed to format requesting an integer format. + * * @stable ICU 2.6 */ public static final int FORMAT_INTEGER = INTEGERSTYLE; /** - * Returns true if this factory is visible. Default is true. - * If not visible, the locales supported by this factory will not - * be listed by getAvailableLocales. This value must not change. + * Returns true if this factory is visible. Default is true. If not visible, the locales supported by this + * factory will not be listed by getAvailableLocales. This value must not change. + * * @return true if the factory is visible. * @stable ICU 2.6 */ @@ -810,22 +813,23 @@ public abstract class NumberFormat extends UFormat { } /** - * Returns an immutable collection of the locale names directly - * supported by this factory. + * Returns an immutable collection of the locale names directly supported by this factory. + * * @return the supported locale names. * @stable ICU 2.6 */ - public abstract Set
getSupportedLocaleNames(); + public abstract Set getSupportedLocaleNames(); /** - * Returns a number format of the appropriate type. If the locale - * is not supported, return null. If the locale is supported, but - * the type is not provided by this service, return null. Otherwise - * return an appropriate instance of NumberFormat. - * Note: as of ICU4J 3.2, implementations should override - * this method instead of createFormat(Locale, int). - * @param loc the locale for which to create the format - * @param formatType the type of format + * Returns a number format of the appropriate type. If the locale is not supported, return null. If the locale + * is supported, but the type is not provided by this service, return null. Otherwise return an appropriate + * instance of NumberFormat. Note: as of ICU4J 3.2, implementations should override this method instead + * of createFormat(Locale, int). + * + * @param loc + * the locale for which to create the format + * @param formatType + * the type of format * @return the NumberFormat, or null. * @stable ICU 3.2 */ @@ -834,15 +838,15 @@ public abstract class NumberFormat extends UFormat { } /** - * Returns a number format of the appropriate type. If the locale - * is not supported, return null. If the locale is supported, but - * the type is not provided by this service, return null. Otherwise - * return an appropriate instance of NumberFormat. - * Note: as of ICU4J 3.2, createFormat(ULocale, int) should be - * overridden instead of this method. This method is no longer - * abstract and delegates to that method. - * @param loc the locale for which to create the format - * @param formatType the type of format + * Returns a number format of the appropriate type. If the locale is not supported, return null. If the locale + * is supported, but the type is not provided by this service, return null. Otherwise return an appropriate + * instance of NumberFormat. Note: as of ICU4J 3.2, createFormat(ULocale, int) should be overridden + * instead of this method. This method is no longer abstract and delegates to that method. + * + * @param loc + * the locale for which to create the format + * @param formatType + * the type of format * @return the NumberFormat, or null. * @stable ICU 2.6 */ @@ -858,7 +862,8 @@ public abstract class NumberFormat extends UFormat { } /** - * A NumberFormatFactory that supports a single locale. It can be visible or invisible. + * A NumberFormatFactory that supports a single locale. It can be visible or invisible. + * * @stable ICU 2.6 */ public static abstract class SimpleNumberFormatFactory extends NumberFormatFactory { @@ -867,6 +872,7 @@ public abstract class NumberFormat extends UFormat { /** * Constructs a SimpleNumberFormatFactory with the given locale. + * * @stable ICU 2.6 */ public SimpleNumberFormatFactory(Locale locale) { @@ -874,8 +880,8 @@ public abstract class NumberFormat extends UFormat { } /** - * Constructs a SimpleNumberFormatFactory with the given locale and the - * visibility. + * Constructs a SimpleNumberFormatFactory with the given locale and the visibility. + * * @stable ICU 2.6 */ public SimpleNumberFormatFactory(Locale locale, boolean visible) { @@ -885,6 +891,7 @@ public abstract class NumberFormat extends UFormat { /** * Constructs a SimpleNumberFormatFactory with the given locale. + * * @stable ICU 3.2 */ public SimpleNumberFormatFactory(ULocale locale) { @@ -892,8 +899,8 @@ public abstract class NumberFormat extends UFormat { } /** - * Constructs a SimpleNumberFormatFactory with the given locale and the - * visibility. + * Constructs a SimpleNumberFormatFactory with the given locale and the visibility. + * * @stable ICU 3.2 */ public SimpleNumberFormatFactory(ULocale locale, boolean visible) { @@ -903,6 +910,7 @@ public abstract class NumberFormat extends UFormat { /** * {@inheritDoc} + * * @stable ICU 2.6 */ @Override @@ -912,6 +920,7 @@ public abstract class NumberFormat extends UFormat { /** * {@inheritDoc} + * * @stable ICU 2.6 */ @Override @@ -923,38 +932,43 @@ public abstract class NumberFormat extends UFormat { // shim so we can build without service code static abstract class NumberFormatShim { abstract Locale[] getAvailableLocales(); + abstract ULocale[] getAvailableULocales(); + abstract Object registerFactory(NumberFormatFactory f); + abstract boolean unregister(Object k); + abstract NumberFormat createInstance(ULocale l, int k); } private static NumberFormatShim shim; + private static NumberFormatShim getShim() { // Note: this instantiation is safe on loose-memory-model configurations // despite lack of synchronization, since the shim instance has no state-- - // it's all in the class init. The worst problem is we might instantiate + // it's all in the class init. The worst problem is we might instantiate // two shim instances, but they'll share the same state so that's ok. if (shim == null) { try { Class> cls = Class.forName("com.ibm.icu.text.NumberFormatServiceShim"); - shim = (NumberFormatShim)cls.newInstance(); + shim = (NumberFormatShim) cls.newInstance(); } - ///CLOVER:OFF - catch (MissingResourceException e){ + // /CLOVER:OFF + catch (MissingResourceException e) { throw e; - } - catch (Exception e) { - // e.printStackTrace(); + } catch (Exception e) { + // e.printStackTrace(); throw new RuntimeException(e.getMessage()); } - ///CLOVER:ON + // /CLOVER:ON } return shim; } /** * Returns the list of Locales for which NumberFormats are available. + * * @return the available locales * @stable ICU 2.0 */ @@ -967,6 +981,7 @@ public abstract class NumberFormat extends UFormat { /** * {@icu} Returns the list of Locales for which NumberFormats are available. + * * @return the available locales * @draft ICU 3.2 (retain) * @provisional This API might change or be removed in a future release. @@ -979,15 +994,15 @@ public abstract class NumberFormat extends UFormat { } /** - * {@icu} Registers a new NumberFormatFactory. The factory is adopted by - * the service and must not be modified. The returned object is a - * key that can be used to unregister this factory. + * {@icu} Registers a new NumberFormatFactory. The factory is adopted by the service and must not be modified. The + * returned object is a key that can be used to unregister this factory. * - * Because ICU may choose to cache NumberFormat objects internally, this must - * be called at application startup, prior to any calls to - * NumberFormat.getInstance to avoid undefined behavior. + *
+ * Because ICU may choose to cache NumberFormat objects internally, this must be called at application startup, + * prior to any calls to NumberFormat.getInstance to avoid undefined behavior. * - * @param factory the factory to register + * @param factory + * the factory to register * @return a key with which to unregister the factory * @stable ICU 2.6 */ @@ -999,9 +1014,11 @@ public abstract class NumberFormat extends UFormat { } /** - * {@icu} Unregisters the factory or instance associated with this key (obtained from - * registerInstance or registerFactory). - * @param registryKey a key obtained from registerFactory + * {@icu} Unregisters the factory or instance associated with this key (obtained from registerInstance or + * registerFactory). + * + * @param registryKey + * a key obtained from registerFactory * @return true if the object was successfully unregistered * @stable ICU 2.6 */ @@ -1021,6 +1038,7 @@ public abstract class NumberFormat extends UFormat { /** * Overrides hashCode. + * * @stable ICU 2.0 */ @Override @@ -1030,34 +1048,33 @@ public abstract class NumberFormat extends UFormat { } /** - * Overrides equals. - * Two NumberFormats are equal if they are of the same class - * and the settings (groupingUsed, parseIntegerOnly, maximumIntegerDigits, etc. - * are equal. - * @param obj the object to compare against + * Overrides equals. Two NumberFormats are equal if they are of the same class and the settings (groupingUsed, + * parseIntegerOnly, maximumIntegerDigits, etc. are equal. + * + * @param obj + * the object to compare against * @return true if the object is equal to this. * @stable ICU 2.0 */ @Override public boolean equals(Object obj) { - if (obj == null) return false; + if (obj == null) + return false; if (this == obj) return true; if (getClass() != obj.getClass()) return false; NumberFormat other = (NumberFormat) obj; - return maximumIntegerDigits == other.maximumIntegerDigits - && minimumIntegerDigits == other.minimumIntegerDigits - && maximumFractionDigits == other.maximumFractionDigits - && minimumFractionDigits == other.minimumFractionDigits - && groupingUsed == other.groupingUsed - && parseIntegerOnly == other.parseIntegerOnly - && parseStrict == other.parseStrict - && capitalizationSetting == other.capitalizationSetting; + return maximumIntegerDigits == other.maximumIntegerDigits && minimumIntegerDigits == other.minimumIntegerDigits + && maximumFractionDigits == other.maximumFractionDigits + && minimumFractionDigits == other.minimumFractionDigits && groupingUsed == other.groupingUsed + && parseIntegerOnly == other.parseIntegerOnly && parseStrict == other.parseStrict + && capitalizationSetting == other.capitalizationSetting; } /** * Overrides clone. + * * @stable ICU 2.0 */ @Override @@ -1067,11 +1084,10 @@ public abstract class NumberFormat extends UFormat { } /** - * Returns true if grouping is used in this format. For example, in the - * en_US locale, with grouping on, the number 1234567 will be formatted - * as "1,234,567". The grouping separator as well as the size of each group - * is locale-dependent and is determined by subclasses of NumberFormat. - * Grouping affects both parsing and formatting. + * Returns true if grouping is used in this format. For example, in the en_US locale, with grouping on, the number + * 1234567 will be formatted as "1,234,567". The grouping separator as well as the size of each group is + * locale-dependent and is determined by subclasses of NumberFormat. Grouping affects both parsing and formatting. + * * @return true if grouping is used * @see #setGroupingUsed * @stable ICU 2.0 @@ -1081,10 +1097,11 @@ public abstract class NumberFormat extends UFormat { } /** - * Sets whether or not grouping will be used in this format. Grouping - * affects both parsing and formatting. + * Sets whether or not grouping will be used in this format. Grouping affects both parsing and formatting. + * * @see #isGroupingUsed - * @param newValue true to use grouping. + * @param newValue + * true to use grouping. * @stable ICU 2.0 */ public void setGroupingUsed(boolean newValue) { @@ -1092,10 +1109,10 @@ public abstract class NumberFormat extends UFormat { } /** - * Returns the maximum number of digits allowed in the integer portion of a - * number. The default value is 40, which subclasses can override. - * When formatting, the exact behavior when this value is exceeded is - * subclass-specific. When parsing, this has no effect. + * Returns the maximum number of digits allowed in the integer portion of a number. The default value is 40, which + * subclasses can override. When formatting, the exact behavior when this value is exceeded is subclass-specific. + * When parsing, this has no effect. + * * @return the maximum number of integer digits * @see #setMaximumIntegerDigits * @stable ICU 2.0 @@ -1105,29 +1122,27 @@ public abstract class NumberFormat extends UFormat { } /** - * Sets the maximum number of digits allowed in the integer portion of a - * number. This must be >= minimumIntegerDigits. If the - * new value for maximumIntegerDigits is less than the current value - * of minimumIntegerDigits, then minimumIntegerDigits will also be set to - * the new value. - * @param newValue the maximum number of integer digits to be shown; if - * less than zero, then zero is used. Subclasses might enforce an - * upper limit to this value appropriate to the numeric type being formatted. + * Sets the maximum number of digits allowed in the integer portion of a number. This must be >= + * minimumIntegerDigits. If the new value for maximumIntegerDigits is less than the current value of + * minimumIntegerDigits, then minimumIntegerDigits will also be set to the new value. + * + * @param newValue + * the maximum number of integer digits to be shown; if less than zero, then zero is used. Subclasses + * might enforce an upper limit to this value appropriate to the numeric type being formatted. * @see #getMaximumIntegerDigits * @stable ICU 2.0 */ public void setMaximumIntegerDigits(int newValue) { - maximumIntegerDigits = Math.max(0,newValue); + maximumIntegerDigits = Math.max(0, newValue); if (minimumIntegerDigits > maximumIntegerDigits) minimumIntegerDigits = maximumIntegerDigits; } /** - * Returns the minimum number of digits allowed in the integer portion of a - * number. The default value is 1, which subclasses can override. - * When formatting, if this value is not reached, numbers are padded on the - * left with the locale-specific '0' character to ensure at least this - * number of integer digits. When parsing, this has no effect. + * Returns the minimum number of digits allowed in the integer portion of a number. The default value is 1, which + * subclasses can override. When formatting, if this value is not reached, numbers are padded on the left with the + * locale-specific '0' character to ensure at least this number of integer digits. When parsing, this has no effect. + * * @return the minimum number of integer digits * @see #setMinimumIntegerDigits * @stable ICU 2.0 @@ -1137,29 +1152,27 @@ public abstract class NumberFormat extends UFormat { } /** - * Sets the minimum number of digits allowed in the integer portion of a - * number. This must be <= maximumIntegerDigits. If the - * new value for minimumIntegerDigits is more than the current value - * of maximumIntegerDigits, then maximumIntegerDigits will also be set to - * the new value. - * @param newValue the minimum number of integer digits to be shown; if - * less than zero, then zero is used. Subclasses might enforce an - * upper limit to this value appropriate to the numeric type being formatted. + * Sets the minimum number of digits allowed in the integer portion of a number. This must be <= + * maximumIntegerDigits. If the new value for minimumIntegerDigits is more than the current value of + * maximumIntegerDigits, then maximumIntegerDigits will also be set to the new value. + * + * @param newValue + * the minimum number of integer digits to be shown; if less than zero, then zero is used. Subclasses + * might enforce an upper limit to this value appropriate to the numeric type being formatted. * @see #getMinimumIntegerDigits * @stable ICU 2.0 */ public void setMinimumIntegerDigits(int newValue) { - minimumIntegerDigits = Math.max(0,newValue); + minimumIntegerDigits = Math.max(0, newValue); if (minimumIntegerDigits > maximumIntegerDigits) maximumIntegerDigits = minimumIntegerDigits; } /** - * Returns the maximum number of digits allowed in the fraction - * portion of a number. The default value is 3, which subclasses - * can override. When formatting, the exact behavior when this - * value is exceeded is subclass-specific. When parsing, this has - * no effect. + * Returns the maximum number of digits allowed in the fraction portion of a number. The default value is 3, which + * subclasses can override. When formatting, the exact behavior when this value is exceeded is subclass-specific. + * When parsing, this has no effect. + * * @return the maximum number of fraction digits * @see #setMaximumFractionDigits * @stable ICU 2.0 @@ -1169,29 +1182,28 @@ public abstract class NumberFormat extends UFormat { } /** - * Sets the maximum number of digits allowed in the fraction portion of a - * number. This must be >= minimumFractionDigits. If the - * new value for maximumFractionDigits is less than the current value - * of minimumFractionDigits, then minimumFractionDigits will also be set to - * the new value. - * @param newValue the maximum number of fraction digits to be shown; if - * less than zero, then zero is used. The concrete subclass may enforce an - * upper limit to this value appropriate to the numeric type being formatted. + * Sets the maximum number of digits allowed in the fraction portion of a number. This must be >= + * minimumFractionDigits. If the new value for maximumFractionDigits is less than the current value of + * minimumFractionDigits, then minimumFractionDigits will also be set to the new value. + * + * @param newValue + * the maximum number of fraction digits to be shown; if less than zero, then zero is used. The concrete + * subclass may enforce an upper limit to this value appropriate to the numeric type being formatted. * @see #getMaximumFractionDigits * @stable ICU 2.0 */ public void setMaximumFractionDigits(int newValue) { - maximumFractionDigits = Math.max(0,newValue); + maximumFractionDigits = Math.max(0, newValue); if (maximumFractionDigits < minimumFractionDigits) minimumFractionDigits = maximumFractionDigits; } /** - * Returns the minimum number of digits allowed in the fraction portion of a - * number. The default value is 0, which subclasses can override. - * When formatting, if this value is not reached, numbers are padded on - * the right with the locale-specific '0' character to ensure at least - * this number of fraction digits. When parsing, this has no effect. + * Returns the minimum number of digits allowed in the fraction portion of a number. The default value is 0, which + * subclasses can override. When formatting, if this value is not reached, numbers are padded on the right with the + * locale-specific '0' character to ensure at least this number of fraction digits. When parsing, this has no + * effect. + * * @return the minimum number of fraction digits * @see #setMinimumFractionDigits * @stable ICU 2.0 @@ -1201,31 +1213,29 @@ public abstract class NumberFormat extends UFormat { } /** - * Sets the minimum number of digits allowed in the fraction portion of a - * number. This must be <= maximumFractionDigits. If the - * new value for minimumFractionDigits exceeds the current value - * of maximumFractionDigits, then maximumFractionDigits will also be set to - * the new value. - * @param newValue the minimum number of fraction digits to be shown; if - * less than zero, then zero is used. Subclasses might enforce an - * upper limit to this value appropriate to the numeric type being formatted. + * Sets the minimum number of digits allowed in the fraction portion of a number. This must be <= + * maximumFractionDigits. If the new value for minimumFractionDigits exceeds the current value of + * maximumFractionDigits, then maximumFractionDigits will also be set to the new value. + * + * @param newValue + * the minimum number of fraction digits to be shown; if less than zero, then zero is used. Subclasses + * might enforce an upper limit to this value appropriate to the numeric type being formatted. * @see #getMinimumFractionDigits * @stable ICU 2.0 */ public void setMinimumFractionDigits(int newValue) { - minimumFractionDigits = Math.max(0,newValue); + minimumFractionDigits = Math.max(0, newValue); if (maximumFractionDigits < minimumFractionDigits) maximumFractionDigits = minimumFractionDigits; } /** - * Sets the Currency object used to display currency - * amounts. This takes effect immediately, if this format is a - * currency format. If this format is not a currency format, then - * the currency object is used if and when this object becomes a - * currency format. - * @param theCurrency new currency object to use. May be null for - * some subclasses. + * Sets the Currency object used to display currency amounts. This takes effect immediately, if this format + * is a currency format. If this format is not a currency format, then the currency object is used if and when this + * object becomes a currency format. + * + * @param theCurrency + * new currency object to use. May be null for some subclasses. * @stable ICU 2.6 */ public void setCurrency(Currency theCurrency) { @@ -1233,8 +1243,8 @@ public abstract class NumberFormat extends UFormat { } /** - * Returns the Currency object used to display currency - * amounts. This may be null. + * Returns the Currency object used to display currency amounts. This may be null. + * * @stable ICU 2.6 */ public Currency getCurrency() { @@ -1242,9 +1252,9 @@ public abstract class NumberFormat extends UFormat { } /** - * Returns the currency in effect for this formatter. Subclasses - * should override this method as needed. Unlike getCurrency(), - * this method should never return null. + * Returns the currency in effect for this formatter. Subclasses should override this method as needed. Unlike + * getCurrency(), this method should never return null. + * * @return a non-null Currency * @internal * @deprecated This API is ICU internal only. @@ -1263,55 +1273,53 @@ public abstract class NumberFormat extends UFormat { } /** - * Returns the rounding mode used in this NumberFormat. The default implementation of - * tis method in NumberFormat always throws
UnsupportedOperationException
. - * @return A rounding mode, betweenBigDecimal.ROUND_UP
- * andBigDecimal.ROUND_UNNECESSARY
. + * Returns the rounding mode used in this NumberFormat. The default implementation of tis method in NumberFormat + * always throwsUnsupportedOperationException
. + * + * @return A rounding mode, betweenBigDecimal.ROUND_UP
andBigDecimal.ROUND_UNNECESSARY
. * @see #setRoundingMode(int) * @stable ICU 4.0 */ public int getRoundingMode() { - throw new UnsupportedOperationException( - "getRoundingMode must be implemented by the subclass implementation."); + throw new UnsupportedOperationException("getRoundingMode must be implemented by the subclass implementation."); } /** - * Set the rounding mode used in this NumberFormat. The default implementation of - * tis method in NumberFormat always throwsUnsupportedOperationException
. - * @param roundingMode A rounding mode, between - *BigDecimal.ROUND_UP
and - *BigDecimal.ROUND_UNNECESSARY
. + * Set the rounding mode used in this NumberFormat. The default implementation of tis method in NumberFormat always + * throwsUnsupportedOperationException
. + * + * @param roundingMode + * A rounding mode, betweenBigDecimal.ROUND_UP
and + *BigDecimal.ROUND_UNNECESSARY
. * @see #getRoundingMode() * @stable ICU 4.0 */ public void setRoundingMode(int roundingMode) { - throw new UnsupportedOperationException( - "setRoundingMode must be implemented by the subclass implementation."); + throw new UnsupportedOperationException("setRoundingMode must be implemented by the subclass implementation."); } - /** * Returns a specific style number format for a specific locale. - * @param desiredLocale the specific locale. - * @param choice number format style - * @throws IllegalArgumentException if choice is not one of - * NUMBERSTYLE, CURRENCYSTYLE, - * PERCENTSTYLE, SCIENTIFICSTYLE, - * INTEGERSTYLE, ISOCURRENCYSTYLE, - * PLURALCURRENCYSTYLE and ACCOUNTSTYLE. + * + * @param desiredLocale + * the specific locale. + * @param choice + * number format style + * @throws IllegalArgumentException + * if choice is not one of NUMBERSTYLE, CURRENCYSTYLE, PERCENTSTYLE, SCIENTIFICSTYLE, INTEGERSTYLE, + * ISOCURRENCYSTYLE, PLURALCURRENCYSTYLE and ACCOUNTSTYLE. * @stable ICU 4.2 */ public static NumberFormat getInstance(ULocale desiredLocale, int choice) { - if (choice < NUMBERSTYLE || choice > ACCOUNTINGCURRENCYSTYLE) { - throw new IllegalArgumentException( - "choice should be from NUMBERSTYLE to PLURALCURRENCYSTYLE"); + if (choice < NUMBERSTYLE || choice > CASHCURRENCYSTYLE) { + throw new IllegalArgumentException("choice should be from NUMBERSTYLE to PLURALCURRENCYSTYLE"); } -// if (shim == null) { -// return createInstance(desiredLocale, choice); -// } else { -// // TODO: shims must call setLocale() on object they create -// return getShim().createInstance(desiredLocale, choice); -// } + // if (shim == null) { + // return createInstance(desiredLocale, choice); + // } else { + // // TODO: shims must call setLocale() on object they create + // return getShim().createInstance(desiredLocale, choice); + // } return getShim().createInstance(desiredLocale, choice); } @@ -1331,9 +1339,10 @@ public abstract class NumberFormat extends UFormat { // This style wont work for currency plural format. // For currency plural format, the pattern is get from // the locale (from CurrencyUnitPatterns) without override. - if(choice == CURRENCYSTYLE || choice == ISOCURRENCYSTYLE || choice == ACCOUNTINGCURRENCYSTYLE){ + if (choice == CURRENCYSTYLE || choice == ISOCURRENCYSTYLE || choice == ACCOUNTINGCURRENCYSTYLE + || choice == CASHCURRENCYSTYLE) { String temp = symbols.getCurrencyPattern(); - if(temp!=null){ + if (temp != null) { pattern = temp; } } @@ -1346,13 +1355,13 @@ public abstract class NumberFormat extends UFormat { // Get the numbering system NumberingSystem ns = NumberingSystem.getInstance(desiredLocale); - if ( ns == null ) { + if (ns == null) { return null; } NumberFormat format; - if ( ns != null && ns.isAlgorithmic()) { + if (ns != null && ns.isAlgorithmic()) { String nsDesc; String nsRuleSetGroup; String nsRuleSetName; @@ -1363,41 +1372,46 @@ public abstract class NumberFormat extends UFormat { int firstSlash = nsDesc.indexOf("/"); int lastSlash = nsDesc.lastIndexOf("/"); - if ( lastSlash > firstSlash ) { - String nsLocID = nsDesc.substring(0,firstSlash); - nsRuleSetGroup = nsDesc.substring(firstSlash+1,lastSlash); - nsRuleSetName = nsDesc.substring(lastSlash+1); + if (lastSlash > firstSlash) { + String nsLocID = nsDesc.substring(0, firstSlash); + nsRuleSetGroup = nsDesc.substring(firstSlash + 1, lastSlash); + nsRuleSetName = nsDesc.substring(lastSlash + 1); - nsLoc = new ULocale(nsLocID); - if ( nsRuleSetGroup.equals("SpelloutRules")) { - desiredRulesType = RuleBasedNumberFormat.SPELLOUT; - } + nsLoc = new ULocale(nsLocID); + if (nsRuleSetGroup.equals("SpelloutRules")) { + desiredRulesType = RuleBasedNumberFormat.SPELLOUT; + } } else { nsLoc = desiredLocale; nsRuleSetName = nsDesc; } - RuleBasedNumberFormat r = new RuleBasedNumberFormat(nsLoc,desiredRulesType); + RuleBasedNumberFormat r = new RuleBasedNumberFormat(nsLoc, desiredRulesType); r.setDefaultRuleSet(nsRuleSetName); format = r; } else { DecimalFormat f = new DecimalFormat(pattern, symbols, choice); - // System.out.println("loc: " + desiredLocale + " choice: " + choice + " pat: " + pattern + " sym: " + symbols + " result: " + format); + // System.out.println("loc: " + desiredLocale + " choice: " + choice + " pat: " + pattern + " sym: " + + // symbols + " result: " + format); - /*Bug 4408066 - Add codes for the new method getIntegerInstance() [Richard/GCL] - */ + /* + * Bug 4408066 Add codes for the new method getIntegerInstance() [Richard/GCL] + */ // TODO: revisit this -- this is almost certainly not the way we want - // to do this. aliu 1/6/2004 + // to do this. aliu 1/6/2004 + if (choice == CASHCURRENCYSTYLE) { + f.setCurrencyUsage(CurrencyUsage.CASH); + } + if (choice == INTEGERSTYLE) { f.setMaximumFractionDigits(0); f.setDecimalSeparatorAlwaysShown(false); f.setParseIntegerOnly(true); } format = f; - } + } // TODO: the actual locale of the *pattern* may differ from that - // for the *symbols*. For now, we use the data for the symbols. + // for the *symbols*. For now, we use the data for the symbols. // Revisit this. ULocale valid = symbols.getLocale(ULocale.VALID_LOCALE); ULocale actual = symbols.getLocale(ULocale.ACTUAL_LOCALE); @@ -1408,8 +1422,11 @@ public abstract class NumberFormat extends UFormat { /** * Returns the pattern for the provided locale and choice. - * @param forLocale the locale of the data. - * @param choice the pattern format. + * + * @param forLocale + * the locale of the data. + * @param choice + * the pattern format. * @return the pattern * @deprecated ICU 3.4 subclassers should override getPattern(ULocale, int) instead of this method. */ @@ -1420,55 +1437,49 @@ public abstract class NumberFormat extends UFormat { /** * Returns the pattern for the provided locale and choice. - * @param forLocale the locale of the data. - * @param choice the pattern format. + * + * @param forLocale + * the locale of the data. + * @param choice + * the pattern format. * @return the pattern * @stable ICU 3.2 */ protected static String getPattern(ULocale forLocale, int choice) { - /* The following code takes care of a few cases where the - * resource data in the underlying JDK lags the new features - * we have added to ICU4J: scientific notation, rounding, and - * secondary grouping. - * - * We detect these cases here and return various hard-coded - * resource data. This is the simplest solution for now, but - * it is not a good long-term mechanism. - * - * We should replace this code with a data-driven mechanism - * that reads the bundle com.ibm.icu.impl.data.LocaleElements - * and parses an exception table that overrides the standard - * data at java.text.resource.LocaleElements*.java. - * Alternatively, we should create our own copy of the - * resource data, and use that exclusively. + /* + * The following code takes care of a few cases where the resource data in the underlying JDK lags the new + * features we have added to ICU4J: scientific notation, rounding, and secondary grouping. + * + * We detect these cases here and return various hard-coded resource data. This is the simplest solution for + * now, but it is not a good long-term mechanism. + * + * We should replace this code with a data-driven mechanism that reads the bundle + * com.ibm.icu.impl.data.LocaleElements and parses an exception table that overrides the standard data at + * java.text.resource.LocaleElements*.java. Alternatively, we should create our own copy of the resource data, + * and use that exclusively. */ // TEMPORARY, until we get scientific patterns into the main - // resources: Retrieve scientific patterns from our resources. - //if (choice == SCIENTIFICSTYLE) { - // Temporarily hard code; retrieve from resource later - /*For ICU compatibility [Richard/GCL]*/ - // return "#E0"; - // return NumberFormat.getBaseStringArray("NumberPatterns")[SCIENTIFICSTYLE]; - //} + // resources: Retrieve scientific patterns from our resources. + // if (choice == SCIENTIFICSTYLE) { + // Temporarily hard code; retrieve from resource later + /* For ICU compatibility [Richard/GCL] */ + // return "#E0"; + // return NumberFormat.getBaseStringArray("NumberPatterns")[SCIENTIFICSTYLE]; + // } - /* {dlf} - // Try the cache first - String[] numberPatterns = (String[]) cachedLocaleData.get(forLocale); - if (numberPatterns == null) { - OverlayBundle resource = new OverlayBundle(new String[] - { "com.ibm.icu.impl.data.LocaleElements", RESOURCE_BASE }, forLocale); - numberPatterns = resource.getStringArray("NumberPatterns"); - // Update the cache - cachedLocaleData.put(forLocale, numberPatterns); - } - */ + /* + * {dlf} // Try the cache first String[] numberPatterns = (String[]) cachedLocaleData.get(forLocale); if + * (numberPatterns == null) { OverlayBundle resource = new OverlayBundle(new String[] { + * "com.ibm.icu.impl.data.LocaleElements", RESOURCE_BASE }, forLocale); numberPatterns = + * resource.getStringArray("NumberPatterns"); // Update the cache cachedLocaleData.put(forLocale, + * numberPatterns); } + */ - /* for ISOCURRENCYSTYLE and PLURALCURRENCYSTYLE, - * the pattern is the same as the pattern of CURRENCYSTYLE - * but by replacing the single currency sign with - * double currency sign or triple currency sign. + /* + * for ISOCURRENCYSTYLE and PLURALCURRENCYSTYLE, the pattern is the same as the pattern of CURRENCYSTYLE but by + * replacing the single currency sign with double currency sign or triple currency sign. */ String patternKey = null; switch (choice) { @@ -1477,6 +1488,7 @@ public abstract class NumberFormat extends UFormat { patternKey = "decimalFormat"; break; case CURRENCYSTYLE: + case CASHCURRENCYSTYLE: case ISOCURRENCYSTYLE: case PLURALCURRENCYSTYLE: patternKey = "currencyFormat"; @@ -1496,15 +1508,15 @@ public abstract class NumberFormat extends UFormat { break; } - ICUResourceBundle rb = (ICUResourceBundle)UResourceBundle. - getBundleInstance(ICUResourceBundle.ICU_BASE_NAME, forLocale); + ICUResourceBundle rb = (ICUResourceBundle) UResourceBundle.getBundleInstance(ICUResourceBundle.ICU_BASE_NAME, + forLocale); NumberingSystem ns = NumberingSystem.getInstance(forLocale); String result = null; try { - result = rb.getStringWithFallback("NumberElements/" + ns.getName() + "/patterns/"+ patternKey); - } catch ( MissingResourceException ex ) { - result = rb.getStringWithFallback("NumberElements/latn/patterns/"+ patternKey); + result = rb.getStringWithFallback("NumberElements/" + ns.getName() + "/patterns/" + patternKey); + } catch (MissingResourceException ex) { + result = rb.getStringWithFallback("NumberElements/latn/patterns/" + patternKey); } return result; @@ -1512,20 +1524,16 @@ public abstract class NumberFormat extends UFormat { /** * First, read in the default serializable data. - * - * Then, ifserialVersionOnStream
is less than 1, indicating that - * the stream was written by JDK 1.1, - * set theint
fields such asmaximumIntegerDigits
- * to be equal to thebyte
fields such asmaxIntegerDigits
, - * since theint
fields were not present in JDK 1.1. - * Finally, set serialVersionOnStream back to the maximum allowed value so that - * default serialization will work properly if this object is streamed out again. + * + * Then, ifserialVersionOnStream
is less than 1, indicating that the stream was written by JDK 1.1, + * set theint
fields such asmaximumIntegerDigits
to be equal to thebyte
+ * fields such asmaxIntegerDigits
, since theint
fields were not present in JDK 1.1. + * Finally, set serialVersionOnStream back to the maximum allowed value so that default serialization will work + * properly if this object is streamed out again. */ - private void readObject(ObjectInputStream stream) - throws IOException, ClassNotFoundException - { + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); - ///CLOVER:OFF + // /CLOVER:OFF // we don't have serialization data for this format if (serialVersionOnStream < 1) { // Didn't have additional int fields, reassign to use them. @@ -1538,188 +1546,164 @@ public abstract class NumberFormat extends UFormat { // Didn't have capitalizationSetting, set it to default capitalizationSetting = DisplayContext.CAPITALIZATION_NONE; } - ///CLOVER:ON - /*Bug 4185761 - Validate the min and max fields [Richard/GCL] - */ - if (minimumIntegerDigits > maximumIntegerDigits || - minimumFractionDigits > maximumFractionDigits || - minimumIntegerDigits < 0 || minimumFractionDigits < 0) { + + // /CLOVER:ON + /* + * Bug 4185761 Validate the min and max fields [Richard/GCL] + */ + if (minimumIntegerDigits > maximumIntegerDigits || minimumFractionDigits > maximumFractionDigits + || minimumIntegerDigits < 0 || minimumFractionDigits < 0) { throw new InvalidObjectException("Digit count range invalid"); } + serialVersionOnStream = currentSerialVersion; } /** - * Write out the default serializable data, after first setting - * thebyte
fields such asmaxIntegerDigits
to be - * equal to theint
fields such asmaximumIntegerDigits
- * (or toByte.MAX_VALUE
, whichever is smaller), for compatibility + * Write out the default serializable data, after first setting thebyte
fields such as + *maxIntegerDigits
to be equal to theint
fields such as + *maximumIntegerDigits
(or toByte.MAX_VALUE
, whichever is smaller), for compatibility * with the JDK 1.1 version of the stream format. */ - private void writeObject(ObjectOutputStream stream) - throws IOException - { - maxIntegerDigits = (maximumIntegerDigits > Byte.MAX_VALUE) ? Byte.MAX_VALUE : - (byte)maximumIntegerDigits; - minIntegerDigits = (minimumIntegerDigits > Byte.MAX_VALUE) ? Byte.MAX_VALUE : - (byte)minimumIntegerDigits; - maxFractionDigits = (maximumFractionDigits > Byte.MAX_VALUE) ? Byte.MAX_VALUE : - (byte)maximumFractionDigits; - minFractionDigits = (minimumFractionDigits > Byte.MAX_VALUE) ? Byte.MAX_VALUE : - (byte)minimumFractionDigits; + private void writeObject(ObjectOutputStream stream) throws IOException { + maxIntegerDigits = (maximumIntegerDigits > Byte.MAX_VALUE) ? Byte.MAX_VALUE : (byte) maximumIntegerDigits; + minIntegerDigits = (minimumIntegerDigits > Byte.MAX_VALUE) ? Byte.MAX_VALUE : (byte) minimumIntegerDigits; + maxFractionDigits = (maximumFractionDigits > Byte.MAX_VALUE) ? Byte.MAX_VALUE : (byte) maximumFractionDigits; + minFractionDigits = (minimumFractionDigits > Byte.MAX_VALUE) ? Byte.MAX_VALUE : (byte) minimumFractionDigits; stream.defaultWriteObject(); } -// Unused -- Alan 2003-05 -// /** -// * Cache to hold the NumberPatterns of a Locale. -// */ -// private static final Hashtable cachedLocaleData = new Hashtable(3); + // Unused -- Alan 2003-05 + // /** + // * Cache to hold the NumberPatterns of a Locale. + // */ + // private static final Hashtable cachedLocaleData = new Hashtable(3); - private static final char[] doubleCurrencySign = {0xA4, 0xA4}; - private static final String doubleCurrencyStr = new String(doubleCurrencySign); - - /*Bug 4408066 - Add Field for the new method getIntegerInstance() [Richard/GCL] - */ + private static final char[] doubleCurrencySign = { 0xA4, 0xA4 }; + private static final String doubleCurrencyStr = new String(doubleCurrencySign); + /* + * Bug 4408066 Add Field for the new method getIntegerInstance() [Richard/GCL] + */ /** - * True if the the grouping (i.e. thousands) separator is used when - * formatting and parsing numbers. - * + * True if the the grouping (i.e. thousands) separator is used when formatting and parsing numbers. + * * @serial * @see #isGroupingUsed */ private boolean groupingUsed = true; /** - * The maximum number of digits allowed in the integer portion of a - * number.maxIntegerDigits
must be greater than or equal to - *minIntegerDigits
. + * The maximum number of digits allowed in the integer portion of a number.maxIntegerDigits
must be + * greater than or equal tominIntegerDigits
. *- * Note: This field exists only for serialization - * compatibility with JDK 1.1. In JDK 1.2 and higher, the new - *
int
fieldmaximumIntegerDigits
is used instead. - * When writing to a stream,maxIntegerDigits
is set to - *maximumIntegerDigits
orByte.MAX_VALUE
, - * whichever is smaller. When reading from a stream, this field is used - * only ifserialVersionOnStream
is less than 1. - * + * Note: This field exists only for serialization compatibility with JDK 1.1. In JDK 1.2 and + * higher, the newint
fieldmaximumIntegerDigits
is used instead. When writing to a + * stream,maxIntegerDigits
is set tomaximumIntegerDigits
orByte.MAX_VALUE
, + * whichever is smaller. When reading from a stream, this field is used only ifserialVersionOnStream
+ * is less than 1. + * * @serial * @see #getMaximumIntegerDigits */ - private byte maxIntegerDigits = 40; + private byte maxIntegerDigits = 40; /** - * The minimum number of digits allowed in the integer portion of a - * number.minimumIntegerDigits
must be less than or equal to - *maximumIntegerDigits
. + * The minimum number of digits allowed in the integer portion of a number.minimumIntegerDigits
must + * be less than or equal tomaximumIntegerDigits
. *- * Note: This field exists only for serialization - * compatibility with JDK 1.1. In JDK 1.2 and higher, the new - *
int
fieldminimumIntegerDigits
is used instead. - * When writing to a stream,minIntegerDigits
is set to - *minimumIntegerDigits
orByte.MAX_VALUE
, - * whichever is smaller. When reading from a stream, this field is used - * only ifserialVersionOnStream
is less than 1. - * + * Note: This field exists only for serialization compatibility with JDK 1.1. In JDK 1.2 and + * higher, the newint
fieldminimumIntegerDigits
is used instead. When writing to a + * stream,minIntegerDigits
is set tominimumIntegerDigits
orByte.MAX_VALUE
, + * whichever is smaller. When reading from a stream, this field is used only ifserialVersionOnStream
+ * is less than 1. + * * @serial * @see #getMinimumIntegerDigits */ - private byte minIntegerDigits = 1; + private byte minIntegerDigits = 1; /** - * The maximum number of digits allowed in the fractional portion of a - * number.maximumFractionDigits
must be greater than or equal to - *minimumFractionDigits
. + * The maximum number of digits allowed in the fractional portion of a number.maximumFractionDigits
+ * must be greater than or equal tominimumFractionDigits
. *- * Note: This field exists only for serialization - * compatibility with JDK 1.1. In JDK 1.2 and higher, the new - *
int
fieldmaximumFractionDigits
is used instead. - * When writing to a stream,maxFractionDigits
is set to - *maximumFractionDigits
orByte.MAX_VALUE
, - * whichever is smaller. When reading from a stream, this field is used - * only ifserialVersionOnStream
is less than 1. - * + * Note: This field exists only for serialization compatibility with JDK 1.1. In JDK 1.2 and + * higher, the newint
fieldmaximumFractionDigits
is used instead. When writing to a + * stream,maxFractionDigits
is set tomaximumFractionDigits
or + *Byte.MAX_VALUE
, whichever is smaller. When reading from a stream, this field is used only if + *serialVersionOnStream
is less than 1. + * * @serial * @see #getMaximumFractionDigits */ - private byte maxFractionDigits = 3; // invariant, >= minFractionDigits + private byte maxFractionDigits = 3; // invariant, >= minFractionDigits /** - * The minimum number of digits allowed in the fractional portion of a - * number.minimumFractionDigits
must be less than or equal to - *maximumFractionDigits
. + * The minimum number of digits allowed in the fractional portion of a number.minimumFractionDigits
+ * must be less than or equal tomaximumFractionDigits
. *- * Note: This field exists only for serialization - * compatibility with JDK 1.1. In JDK 1.2 and higher, the new - *
int
fieldminimumFractionDigits
is used instead. - * When writing to a stream,minFractionDigits
is set to - *minimumFractionDigits
orByte.MAX_VALUE
, - * whichever is smaller. When reading from a stream, this field is used - * only ifserialVersionOnStream
is less than 1. - * + * Note: This field exists only for serialization compatibility with JDK 1.1. In JDK 1.2 and + * higher, the newint
fieldminimumFractionDigits
is used instead. When writing to a + * stream,minFractionDigits
is set tominimumFractionDigits
or + *Byte.MAX_VALUE
, whichever is smaller. When reading from a stream, this field is used only if + *serialVersionOnStream
is less than 1. + * * @serial * @see #getMinimumFractionDigits */ - private byte minFractionDigits = 0; + private byte minFractionDigits = 0; /** * True if this format will parse numbers as integers only. - * + * * @serial * @see #isParseIntegerOnly */ private boolean parseIntegerOnly = false; - // new fields for 1.2. byte is too small for integer digits. + // new fields for 1.2. byte is too small for integer digits. /** - * The maximum number of digits allowed in the integer portion of a - * number.maximumIntegerDigits
must be greater than or equal to - *minimumIntegerDigits
. - * + * The maximum number of digits allowed in the integer portion of a number.maximumIntegerDigits
must + * be greater than or equal tominimumIntegerDigits
. + * * @serial * @see #getMaximumIntegerDigits */ - private int maximumIntegerDigits = 40; + private int maximumIntegerDigits = 40; /** - * The minimum number of digits allowed in the integer portion of a - * number.minimumIntegerDigits
must be less than or equal to - *maximumIntegerDigits
. - * + * The minimum number of digits allowed in the integer portion of a number.minimumIntegerDigits
must + * be less than or equal tomaximumIntegerDigits
. + * * @serial * @see #getMinimumIntegerDigits */ - private int minimumIntegerDigits = 1; + private int minimumIntegerDigits = 1; /** - * The maximum number of digits allowed in the fractional portion of a - * number.maximumFractionDigits
must be greater than or equal to - *minimumFractionDigits
. - * + * The maximum number of digits allowed in the fractional portion of a number.maximumFractionDigits
+ * must be greater than or equal tominimumFractionDigits
. + * * @serial * @see #getMaximumFractionDigits */ - private int maximumFractionDigits = 3; // invariant, >= minFractionDigits + private int maximumFractionDigits = 3; // invariant, >= minFractionDigits /** - * The minimum number of digits allowed in the fractional portion of a - * number.minimumFractionDigits
must be less than or equal to - *maximumFractionDigits
. - * + * The minimum number of digits allowed in the fractional portion of a number.minimumFractionDigits
+ * must be less than or equal tomaximumFractionDigits
. + * * @serial * @see #getMinimumFractionDigits */ - private int minimumFractionDigits = 0; + private int minimumFractionDigits = 0; /** - * Currency object used to format currencies. Subclasses may - * ignore this if they are not currency formats. This will be - * null unless a subclass sets it to a non-null value. + * Currency object used to format currencies. Subclasses may ignore this if they are not currency formats. This will + * be null unless a subclass sets it to a non-null value. + * * @since ICU 2.6 */ private Currency currency; @@ -1727,37 +1711,33 @@ public abstract class NumberFormat extends UFormat { static final int currentSerialVersion = 2; /** - * Describes the version ofNumberFormat
present on the stream. - * Possible values are: + * Describes the version ofNumberFormat
present on the stream. Possible values are: *- *
- * When streaming out a- 0 (or uninitialized): the JDK 1.1 version of the stream format. - * In this version, the
int
fields such as - *maximumIntegerDigits
were not present, and thebyte
- * fields such asmaxIntegerDigits
are used instead. - * - *- 1: the JDK 1.2 version of the stream format. The values of the - *
byte
fields such asmaxIntegerDigits
are ignored, - * and theint
fields such asmaximumIntegerDigits
- * are used instead. - * + *- 0 (or uninitialized): the JDK 1.1 version of the stream format. In this version, the
int
+ * fields such asmaximumIntegerDigits
were not present, and thebyte
fields such as + *maxIntegerDigits
are used instead. + * + *- 1: the JDK 1.2 version of the stream format. The values of the
byte
fields such as + *maxIntegerDigits
are ignored, and theint
fields such as + *maximumIntegerDigits
are used instead. + * *- 2: adds capitalizationSetting. *
NumberFormat
, the most recent format - * (corresponding to the highest allowableserialVersionOnStream
) - * is always written. - * + * When streaming out aNumberFormat
, the most recent format (corresponding to the highest allowable + *serialVersionOnStream
) is always written. + * * @serial */ private int serialVersionOnStream = currentSerialVersion; - // Removed "implements Cloneable" clause. Needs to update serialization + // Removed "implements Cloneable" clause. Needs to update serialization // ID for backward compatibility. private static final long serialVersionUID = -2308460125733713944L; /** - * Empty constructor. Public for compatibility with JDK which lets the - * compiler generate a default public constructor even though this is - * an abstract class. + * Empty constructor. Public for compatibility with JDK which lets the compiler generate a default public + * constructor even though this is an abstract class. + * * @stable ICU 2.6 */ public NumberFormat() { @@ -1768,18 +1748,18 @@ public abstract class NumberFormat extends UFormat { /* * Capitalization context setting, new in ICU 53 + * * @serial */ private DisplayContext capitalizationSetting = DisplayContext.CAPITALIZATION_NONE; /** - * The instances of this inner class are used as attribute keys and values - * in AttributedCharacterIterator that + * The instances of this inner class are used as attribute keys and values in AttributedCharacterIterator that * NumberFormat.formatToCharacterIterator() method returns. *- * There is no public constructor to this class, the only instances are the - * constants defined here. + * There is no public constructor to this class, the only instances are the constants defined here. *
+ * * @stable ICU 3.6 */ public static class Field extends Format.Field { @@ -1841,8 +1821,8 @@ public abstract class NumberFormat extends UFormat { public static final Field CURRENCY = new Field("currency"); /** - * Constructs a new instance of NumberFormat.Field with the given field - * name. + * Constructs a new instance of NumberFormat.Field with the given field name. + * * @stable ICU 3.6 */ protected Field(String fieldName) { @@ -1850,8 +1830,8 @@ public abstract class NumberFormat extends UFormat { } /** - * serizalization method resolve instances to the constant - * NumberFormat.Field values + * serizalization method resolve instances to the constant NumberFormat.Field values + * * @stable ICU 3.6 */ @Override diff --git a/icu4j/main/classes/core/src/com/ibm/icu/util/Currency.java b/icu4j/main/classes/core/src/com/ibm/icu/util/Currency.java index 2e405120bb..a67db8a839 100644 --- a/icu4j/main/classes/core/src/com/ibm/icu/util/Currency.java +++ b/icu4j/main/classes/core/src/com/ibm/icu/util/Currency.java @@ -89,6 +89,28 @@ public class Currency extends MeasureUnit { .add("\u20a8", "\u20b9") .add("\u00a3", "\u20a4"); + /** + * Currency Usage used for Decimal Format + * @draft ICU 54 + */ + public enum CurrencyUsage{ + /** + * a setting to specify currency usage which determines currency digit and rounding + * for official purpose, for example: "50.00 NT$" + * @draft ICU 54 + * @provisional This API might change or be removed in a future release. + */ + STANDARD, + + /** + * a setting to specify currency usage which determines currency digit and rounding + * for cash purpose, for example: "50 NT$" + * @draft ICU 54 + * @provisional This API might change or be removed in a future release. + */ + CASH + } + // begin registry stuff // shim for service code @@ -729,25 +751,50 @@ public class Currency extends MeasureUnit { /** * Returns the number of the number of fraction digits that should * be displayed for this currency. + * This is equivalent to getDefaultFractionDigits(CurrencyUsage.STANDARD); * @return a non-negative number of fraction digits to be * displayed * @stable ICU 2.2 */ public int getDefaultFractionDigits() { + return getDefaultFractionDigits(CurrencyUsage.STANDARD); + } + + /** + * Returns the number of the number of fraction digits that should + * be displayed for this currency with Usage. + * @param Usage the usage of currency(Standard or Cash) + * @return a non-negative number of fraction digits to be + * displayed + * @draft ICU 54 + */ + public int getDefaultFractionDigits(CurrencyUsage Usage) { CurrencyMetaInfo info = CurrencyMetaInfo.getInstance(); - CurrencyDigits digits = info.currencyDigits(subType); + CurrencyDigits digits = info.currencyDigits(subType, Usage); return digits.fractionDigits; } /** * Returns the rounding increment for this currency, or 0.0 if no * rounding is done by this currency. + * This is equivalent to getRoundingIncrement(CurrencyUsage.STANDARD); * @return the non-negative rounding increment, or 0.0 if none * @stable ICU 2.2 */ public double getRoundingIncrement() { + return getRoundingIncrement(CurrencyUsage.STANDARD); + } + + /** + * Returns the rounding increment for this currency, or 0.0 if no + * rounding is done by this currency with the Usage. + * @param Usage the usage of currency(Standard or Cash) + * @return the non-negative rounding increment, or 0.0 if none + * @draft ICU 54 + */ + public double getRoundingIncrement(CurrencyUsage Usage) { CurrencyMetaInfo info = CurrencyMetaInfo.getInstance(); - CurrencyDigits digits = info.currencyDigits(subType); + CurrencyDigits digits = info.currencyDigits(subType, Usage); int data1 = digits.roundingIncrement; @@ -764,7 +811,7 @@ public class Currency extends MeasureUnit { return 0.0; } - // Return data[1] / 10^(data[0]). The only actual rounding data, + // Return data[1] / 10^(data[0]). The only actual rounding data, // as of this writing, is CHF { 2, 25 }. return (double) data1 / POW10[data0]; } diff --git a/icu4j/main/classes/currdata/src/com/ibm/icu/impl/ICUCurrencyMetaInfo.java b/icu4j/main/classes/currdata/src/com/ibm/icu/impl/ICUCurrencyMetaInfo.java index 3eca2de98d..b2329bd221 100644 --- a/icu4j/main/classes/currdata/src/com/ibm/icu/impl/ICUCurrencyMetaInfo.java +++ b/icu4j/main/classes/currdata/src/com/ibm/icu/impl/ICUCurrencyMetaInfo.java @@ -1,6 +1,6 @@ /* ******************************************************************************* - * Copyright (C) 2009-2013, International Business Machines Corporation and * + * Copyright (C) 2009-2014, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* */ @@ -13,6 +13,7 @@ import java.util.List; import java.util.Set; import com.ibm.icu.text.CurrencyMetaInfo; +import com.ibm.icu.util.Currency.CurrencyUsage; /** * ICU's currency meta info data. @@ -46,14 +47,25 @@ public class ICUCurrencyMetaInfo extends CurrencyMetaInfo { @Override public CurrencyDigits currencyDigits(String isoCode) { + return currencyDigits(isoCode, CurrencyUsage.STANDARD); + } + + @Override + public CurrencyDigits currencyDigits(String isoCode, CurrencyUsage currencyPurpose) { ICUResourceBundle b = digitInfo.findWithFallback(isoCode); if (b == null) { b = digitInfo.findWithFallback("DEFAULT"); } int[] data = b.getIntVector(); - return new CurrencyDigits(data[0], data[1]); + if (currencyPurpose == CurrencyUsage.CASH) { + return new CurrencyDigits(data[2], data[3]); + } else if (currencyPurpose == CurrencyUsage.STANDARD) { + return new CurrencyDigits(data[0], data[1]); + } else { + return new CurrencyDigits(data[0], data[1]); + } } - + private
List collect(Collector collector, CurrencyFilter filter) { // We rely on the fact that the data lists the regions in order, and the // priorities in order within region. This means we don't need diff --git a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/NumberFormatTest.java b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/NumberFormatTest.java index 4f9bccc2ca..c8cd0ce0fb 100644 --- a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/NumberFormatTest.java +++ b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/NumberFormatTest.java @@ -23,7 +23,6 @@ import java.util.Locale; import java.util.Set; import com.ibm.icu.dev.test.TestUtil; -import com.ibm.icu.impl.ICUConfig; import com.ibm.icu.impl.LocaleUtility; import com.ibm.icu.impl.data.ResourceReader; import com.ibm.icu.impl.data.TokenIterator; @@ -2735,7 +2734,7 @@ public class NumberFormatTest extends com.ibm.icu.dev.test.TestFmwk { */ public void TestGetInstance() { // Tests "public final static NumberFormat getInstance(int style)" - int maxStyle = NumberFormat.ACCOUNTINGCURRENCYSTYLE; + int maxStyle = NumberFormat.CASHCURRENCYSTYLE; int[] invalid_cases = { NumberFormat.NUMBERSTYLE - 1, NumberFormat.NUMBERSTYLE - 2, maxStyle + 1, maxStyle + 2 }; @@ -3025,24 +3024,26 @@ public class NumberFormatTest extends com.ibm.icu.dev.test.TestFmwk { expect(fmt, "2\uFF61345.67", 2345.67); - // Ticket#7128 + // Ticket#7218 // + // Lenient separator parsing is enabled by default. + // A space character below is interpreted as a + // group separator, even ',' is used as grouping + // separator in the symbols. sym.setGroupingSeparator(','); fmt.setDecimalFormatSymbols(sym); - String skipExtSepParse = ICUConfig.get("com.ibm.icu.text.DecimalFormat.SkipExtendedSeparatorParsing", "false"); - if (skipExtSepParse.equals("true")) { - // When the property SkipExtendedSeparatorParsing is true, - // DecimalFormat does not use the extended equivalent separator - // data and only uses the one in DecimalFormatSymbols. - expect(fmt, "23 456", 23); - } else { - // Lenient separator parsing is enabled by default. - // A space character below is interpreted as a - // group separator, even ',' is used as grouping - // separator in the symbols. - expect(fmt, "12 345", 12345); - } + expect(fmt, "12 345", 12345); + + // When the property SkipExtendedSeparatorParsing is true, + // DecimalFormat does not use the extended equivalent separator + // data and only uses the one in DecimalFormatSymbols. + System.setProperty("com.ibm.icu.text.DecimalFormat.SkipExtendedSeparatorParsing", "true"); + + expect(fmt, "23 456", 23); + + // Set the configuration back to the default + System.setProperty("com.ibm.icu.text.DecimalFormat.SkipExtendedSeparatorParsing", "false"); } /* @@ -3608,4 +3609,72 @@ public class NumberFormatTest extends com.ibm.icu.dev.test.TestFmwk { expect(acfmt, num, fmt, rt); } } + + public void TestCurrencyUsage() { + // the 1st one is checking setter/getter, while the 2nd one checks for getInstance + // compare the Currency and Currency Cash Digits + for(int i=0; i<2; i++){ + String original_expected = "NT$123.57"; + DecimalFormat custom = null; + if(i == 0){ + custom = (DecimalFormat)DecimalFormat.getInstance(new ULocale("en_US@currency=TWD"), DecimalFormat.CURRENCYSTYLE); + + String original = custom.format(123.567); + assertEquals("Test Currency Context", original_expected, original); + + // test the getter + assertEquals("Test Currency Context Purpose", custom.getCurrencyUsage(), Currency.CurrencyUsage.STANDARD); + custom.setCurrencyUsage(Currency.CurrencyUsage.CASH); + assertEquals("Test Currency Context Purpose", custom.getCurrencyUsage(), Currency.CurrencyUsage.CASH); + }else{ + custom = (DecimalFormat)DecimalFormat.getInstance(new ULocale("en_US@currency=TWD"), DecimalFormat.CASHCURRENCYSTYLE); + + // test the getter + assertEquals("Test Currency Context Purpose", custom.getCurrencyUsage(), Currency.CurrencyUsage.CASH); + } + + String cash_currency = custom.format(123.567); + String cash_currency_expected = "NT$124"; + assertEquals("Test Currency Context", cash_currency_expected, cash_currency); + } + + // the 1st one is checking setter/getter, while the 2nd one checks for getInstance + // compare the Currency and Currency Cash Rounding + for(int i=0; i<2; i++){ + String original_rounding_expected = "CA$123.57"; + DecimalFormat fmt = null; + if(i == 0){ + fmt = (DecimalFormat)DecimalFormat.getInstance(new ULocale("en_US@currency=CAD"), DecimalFormat.CURRENCYSTYLE); + + String original_rounding = fmt.format(123.566); + assertEquals("Test Currency Context", original_rounding_expected, original_rounding); + + fmt.setCurrencyUsage(Currency.CurrencyUsage.CASH); + }else{ + fmt = (DecimalFormat)DecimalFormat.getInstance(new ULocale("en_US@currency=CAD"), DecimalFormat.CASHCURRENCYSTYLE); + } + + String cash_rounding_currency = fmt.format(123.567); + String cash__rounding_currency_expected = "CA$123.55"; + assertEquals("Test Currency Context", cash__rounding_currency_expected, cash_rounding_currency); + } + + + // the 1st one is checking setter/getter, while the 2nd one checks for getInstance + // Test the currency change + for(int i=0; i<2; i++){ + DecimalFormat fmt2 = null; + if(i == 1){ + fmt2 = (DecimalFormat)NumberFormat.getInstance(new ULocale("en_US@currency=JPY"), NumberFormat.CURRENCYSTYLE); + fmt2.setCurrencyUsage(Currency.CurrencyUsage.CASH); + }else{ + fmt2 = (DecimalFormat)NumberFormat.getInstance(new ULocale("en_US@currency=JPY"), NumberFormat.CASHCURRENCYSTYLE); + } + + fmt2.setCurrency(Currency.getInstance("TWD")); + String TWD_changed = fmt2.format(123.567); + String TWD_changed_expected = "NT$124"; + assertEquals("Test Currency Context", TWD_changed_expected, TWD_changed); + } + } }