/* * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved * * The original version of this source code and documentation is copyrighted * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These * materials are provided under terms of a License Agreement between Taligent * and Sun. This technology is protected by multiple US and International * patents. This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.text; import java.io.InvalidObjectException;import java.io.IOException;import java.io.ObjectInputStream;import java.math.BigDecimal;import java.math.BigInteger;import java.math.RoundingMode;import java.util.ArrayList;import java.util.Currency;import java.util.Locale;import java.util.ResourceBundle;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentMap;import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicLong;import sun.util.resources.LocaleData; /** * <code>DecimalFormat</code> is a concrete subclass of * <code>NumberFormat</code> that formats decimal numbers. It has a variety of * features designed to make it possible to parse and format numbers in any * locale, including support for Western, Arabic, and Indic digits. It also * supports different kinds of numbers, including integers (123), fixed-point * numbers (123.4), scientific notation (1.23E4), percentages (12%), and * currency amounts ($123). All of these can be localized. * * <p>To obtain a <code>NumberFormat</code> for a specific locale, including the * default locale, call one of <code>NumberFormat</code>'s factory methods, such * as <code>getInstance()</code>. In general, do not call the * <code>DecimalFormat</code> constructors directly, since the * <code>NumberFormat</code> factory methods may return subclasses other than * <code>DecimalFormat</code>. If you need to customize the format object, do * something like this: * * <blockquote><pre> * NumberFormat f = NumberFormat.getInstance(loc); * if (f instanceof DecimalFormat) { * ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true); * } * </pre></blockquote> * * <p>A <code>DecimalFormat</code> comprises a <em>pattern</em> and a set of * <em>symbols</em>. The pattern may be set directly using * <code>applyPattern()</code>, or indirectly using the API methods. The * symbols are stored in a <code>DecimalFormatSymbols</code> object. When using * the <code>NumberFormat</code> factory methods, the pattern and symbols are * read from localized <code>ResourceBundle</code>s. * * <h4>Patterns</h4> * * <code>DecimalFormat</code> patterns have the following syntax: * <blockquote><pre> * <i>Pattern:</i> * <i>PositivePattern</i> * <i>PositivePattern</i> ; <i>NegativePattern</i> * <i>PositivePattern:</i> * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i> * <i>NegativePattern:</i> * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i> * <i>Prefix:</i> * any Unicode characters except \uFFFE, \uFFFF, and special characters * <i>Suffix:</i> * any Unicode characters except \uFFFE, \uFFFF, and special characters * <i>Number:</i> * <i>Integer</i> <i>Exponent<sub>opt</sub></i> * <i>Integer</i> . <i>Fraction</i> <i>Exponent<sub>opt</sub></i> * <i>Integer:</i> * <i>MinimumInteger</i> * # * # <i>Integer</i> * # , <i>Integer</i> * <i>MinimumInteger:</i> * 0 * 0 <i>MinimumInteger</i> * 0 , <i>MinimumInteger</i> * <i>Fraction:</i> * <i>MinimumFraction<sub>opt</sub></i> <i>OptionalFraction<sub>opt</sub></i> * <i>MinimumFraction:</i> * 0 <i>MinimumFraction<sub>opt</sub></i> * <i>OptionalFraction:</i> * # <i>OptionalFraction<sub>opt</sub></i> * <i>Exponent:</i> * E <i>MinimumExponent</i> * <i>MinimumExponent:</i> * 0 <i>MinimumExponent<sub>opt</sub></i> * </pre></blockquote> * * <p>A <code>DecimalFormat</code> pattern contains a positive and negative * subpattern, for example, <code>"#,##0.00;(#,##0.00)"</code>. Each * subpattern has a prefix, numeric part, and suffix. The negative subpattern * is optional; if absent, then the positive subpattern prefixed with the * localized minus sign (<code>'-'</code> in most locales) is used as the * negative subpattern. That is, <code>"0.00"</code> alone is equivalent to * <code>"0.00;-0.00"</code>. If there is an explicit negative subpattern, it * serves only to specify the negative prefix and suffix; the number of digits, * minimal digits, and other characteristics are all the same as the positive * pattern. That means that <code>"#,##0.0#;(#)"</code> produces precisely * the same behavior as <code>"#,##0.0#;(#,##0.0#)"</code>. * * <p>The prefixes, suffixes, and various symbols used for infinity, digits, * thousands separators, decimal separators, etc. may be set to arbitrary * values, and they will appear properly during formatting. However, care must * be taken that the symbols and strings do not conflict, or parsing will be * unreliable. For example, either the positive and negative prefixes or the * suffixes must be distinct for <code>DecimalFormat.parse()</code> to be able * to distinguish positive from negative values. (If they are identical, then * <code>DecimalFormat</code> will behave as if no negative subpattern was * specified.) Another example is that the decimal separator and thousands * separator should be distinct characters, or parsing will be impossible. * * <p>The grouping separator is commonly used for thousands, but in some * countries it separates ten-thousands. The grouping size is a constant number * of digits between the grouping characters, such as 3 for 100,000,000 or 4 for * 1,0000,0000. If you supply a pattern with multiple grouping characters, the * interval between the last one and the end of the integer is the one that is * used. So <code>"#,##,###,####"</code> == <code>"######,####"</code> == * <code>"##,####,####"</code>. * * <h4>Special Pattern Characters</h4> * * <p>Many characters in a pattern are taken literally; they are matched during * parsing and output unchanged during formatting. Special characters, on the * other hand, stand for other characters, strings, or classes of characters. * They must be quoted, unless noted otherwise, if they are to appear in the * prefix or suffix as literals. * * <p>The characters listed here are used in non-localized patterns. Localized * patterns use the corresponding characters taken from this formatter's * <code>DecimalFormatSymbols</code> object instead, and these characters lose * their special status. Two exceptions are the currency sign and quote, which * are not localized. * * <blockquote> * <table border=0 cellspacing=3 cellpadding=0 summary="Chart showing symbol, * location, localized, and meaning."> * <tr bgcolor="#ccccff"> * <th align=left>Symbol * <th align=left>Location * <th align=left>Localized? * <th align=left>Meaning * <tr valign=top> * <td><code>0</code> * <td>Number * <td>Yes * <td>Digit * <tr valign=top bgcolor="#eeeeff"> * <td><code>#</code> * <td>Number * <td>Yes * <td>Digit, zero shows as absent * <tr valign=top> * <td><code>.</code> * <td>Number * <td>Yes * <td>Decimal separator or monetary decimal separator * <tr valign=top bgcolor="#eeeeff"> * <td><code>-</code> * <td>Number * <td>Yes * <td>Minus sign * <tr valign=top> * <td><code>,</code> * <td>Number * <td>Yes * <td>Grouping separator * <tr valign=top bgcolor="#eeeeff"> * <td><code>E</code> * <td>Number * <td>Yes * <td>Separates mantissa and exponent in scientific notation. * <em>Need not be quoted in prefix or suffix.</em> * <tr valign=top> * <td><code>;</code> * <td>Subpattern boundary * <td>Yes * <td>Separates positive and negative subpatterns * <tr valign=top bgcolor="#eeeeff"> * <td><code>%</code> * <td>Prefix or suffix * <td>Yes * <td>Multiply by 100 and show as percentage * <tr valign=top> * <td><code>\u2030</code> * <td>Prefix or suffix * <td>Yes * <td>Multiply by 1000 and show as per mille value * <tr valign=top bgcolor="#eeeeff"> * <td><code>¤</code> (<code>\u00A4</code>) * <td>Prefix or suffix * <td>No * <td>Currency sign, replaced by currency symbol. If * doubled, replaced by international currency symbol. * If present in a pattern, the monetary decimal separator * is used instead of the decimal separator. * <tr valign=top> * <td><code>'</code> * <td>Prefix or suffix * <td>No * <td>Used to quote special characters in a prefix or suffix, * for example, <code>"'#'#"</code> formats 123 to * <code>"#123"</code>. To create a single quote * itself, use two in a row: <code>"# o''clock"</code>. * </table> * </blockquote> * * <h4>Scientific Notation</h4> * * <p>Numbers in scientific notation are expressed as the product of a mantissa * and a power of ten, for example, 1234 can be expressed as 1.234 x 10^3. The * mantissa is often in the range 1.0 <= x < 10.0, but it need not be. * <code>DecimalFormat</code> can be instructed to format and parse scientific * notation <em>only via a pattern</em>; there is currently no factory method * that creates a scientific notation format. In a pattern, the exponent * character immediately followed by one or more digit characters indicates * scientific notation. Example: <code>"0.###E0"</code> formats the number * 1234 as <code>"1.234E3"</code>. * * <ul> * <li>The number of digit characters after the exponent character gives the * minimum exponent digit count. There is no maximum. Negative exponents are * formatted using the localized minus sign, <em>not</em> the prefix and suffix * from the pattern. This allows patterns such as <code>"0.###E0 m/s"</code>. * * <li>The minimum and maximum number of integer digits are interpreted * together: * * <ul> * <li>If the maximum number of integer digits is greater than their minimum number * and greater than 1, it forces the exponent to be a multiple of the maximum * number of integer digits, and the minimum number of integer digits to be * interpreted as 1. The most common use of this is to generate * <em>engineering notation</em>, in which the exponent is a multiple of three, * e.g., <code>"##0.#####E0"</code>. Using this pattern, the number 12345 * formats to <code>"12.345E3"</code>, and 123456 formats to * <code>"123.456E3"</code>. * * <li>Otherwise, the minimum number of integer digits is achieved by adjusting the * exponent. Example: 0.00123 formatted with <code>"00.###E0"</code> yields * <code>"12.3E-4"</code>. * </ul> * * <li>The number of significant digits in the mantissa is the sum of the * <em>minimum integer</em> and <em>maximum fraction</em> digits, and is * unaffected by the maximum integer digits. For example, 12345 formatted with * <code>"##0.##E0"</code> is <code>"12.3E3"</code>. To show all digits, set * the significant digits count to zero. The number of significant digits * does not affect parsing. * * <li>Exponential patterns may not contain grouping separators. * </ul> * * <h4>Rounding</h4> * * <code>DecimalFormat</code> provides rounding modes defined in * {@link java.math.RoundingMode} for formatting. By default, it uses * {@link java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}. * * <h4>Digits</h4> * * For formatting, <code>DecimalFormat</code> uses the ten consecutive * characters starting with the localized zero digit defined in the * <code>DecimalFormatSymbols</code> object as digits. For parsing, these * digits as well as all Unicode decimal digits, as defined by * {@link Character#digit Character.digit}, are recognized. * * <h4>Special Values</h4> * * <p><code>NaN</code> is formatted as a string, which typically has a single character * <code>\uFFFD</code>. This string is determined by the * <code>DecimalFormatSymbols</code> object. This is the only value for which * the prefixes and suffixes are not used. * * <p>Infinity is formatted as a string, which typically has a single character * <code>\u221E</code>, with the positive or negative prefixes and suffixes * applied. The infinity string is determined by the * <code>DecimalFormatSymbols</code> object. * * <p>Negative zero (<code>"-0"</code>) parses to * <ul> * <li><code>BigDecimal(0)</code> if <code>isParseBigDecimal()</code> is * true, * <li><code>Long(0)</code> if <code>isParseBigDecimal()</code> is false * and <code>isParseIntegerOnly()</code> is true, * <li><code>Double(-0.0)</code> if both <code>isParseBigDecimal()</code> * and <code>isParseIntegerOnly()</code> are false. * </ul> * * <h4><a name="synchronization">Synchronization</a></h4> * * <p> * Decimal formats are generally not synchronized. * It is recommended to create separate format instances for each thread. * If multiple threads access a format concurrently, it must be synchronized * externally. * * <h4>Example</h4> * * <blockquote><pre> * <strong>// Print out a number using the localized number, integer, currency, * // and percent format for each locale</strong> * Locale[] locales = NumberFormat.getAvailableLocales(); * double myNumber = -1234.56; * NumberFormat form; * for (int j=0; j<4; ++j) { * System.out.println("FORMAT"); * for (int i = 0; i < locales.length; ++i) { * if (locales[i].getCountry().length() == 0) { * continue; // Skip language-only locales * } * System.out.print(locales[i].getDisplayName()); * switch (j) { * case 0: * form = NumberFormat.getInstance(locales[i]); break; * case 1: * form = NumberFormat.getIntegerInstance(locales[i]); break; * case 2: * form = NumberFormat.getCurrencyInstance(locales[i]); break; * default: * form = NumberFormat.getPercentInstance(locales[i]); break; * } * if (form instanceof DecimalFormat) { * System.out.print(": " + ((DecimalFormat) form).toPattern()); * } * System.out.print(" -> " + form.format(myNumber)); * try { * System.out.println(" -> " + form.parse(form.format(myNumber))); * } catch (ParseException e) {} * } * } * </pre></blockquote> * * @see <a href="http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html">Java Tutorial</a> * @see NumberFormat * @see DecimalFormatSymbols * @see ParsePosition * @author Mark Davis * @author Alan Liu */public class DecimalFormat extends NumberFormat { /** * Creates a DecimalFormat using the default pattern and symbols * for the default locale. This is a convenient way to obtain a * DecimalFormat when internationalization is not the main concern. * <p> * To obtain standard formats for a given locale, use the factory methods * on NumberFormat such as getNumberInstance. These factories will * return the most appropriate sub-class of NumberFormat for a given * locale. * * @see java.text.NumberFormat#getInstance * @see java.text.NumberFormat#getNumberInstance * @see java.text.NumberFormat#getCurrencyInstance * @see java.text.NumberFormat#getPercentInstance */ public DecimalFormat() { Locale def = Locale.getDefault(Locale.Category.FORMAT); // try to get the pattern from the cache String pattern = cachedLocaleData.get(def); if (pattern == null) { /* cache miss */ // Get the pattern for the default locale. ResourceBundle rb = LocaleData.getNumberFormatData(def); String[] all = rb.getStringArray("NumberPatterns"); pattern = all[0]; /* update cache */ cachedLocaleData.putIfAbsent(def, pattern); } // Always applyPattern after the symbols are set this.symbols = new DecimalFormatSymbols(def); applyPattern(pattern, false); } /** * Creates a DecimalFormat using the given pattern and the symbols * for the default locale. This is a convenient way to obtain a * DecimalFormat when internationalization is not the main concern. * <p> * To obtain standard formats for a given locale, use the factory methods * on NumberFormat such as getNumberInstance. These factories will * return the most appropriate sub-class of NumberFormat for a given * locale. * * @param pattern A non-localized pattern string. * @exception NullPointerException if <code>pattern</code> is null * @exception IllegalArgumentException if the given pattern is invalid. * @see java.text.NumberFormat#getInstance * @see java.text.NumberFormat#getNumberInstance * @see java.text.NumberFormat#getCurrencyInstance * @see java.text.NumberFormat#getPercentInstance */ public DecimalFormat(String pattern) { // Always applyPattern after the symbols are set this.symbols = new DecimalFormatSymbols(Locale.getDefault(Locale.Category.FORMAT)); applyPattern(pattern, false); } /** * Creates a DecimalFormat using the given pattern and symbols. * Use this constructor when you need to completely customize the * behavior of the format. * <p> * To obtain standard formats for a given * locale, use the factory methods on NumberFormat such as * getInstance or getCurrencyInstance. If you need only minor adjustments * to a standard format, you can modify the format returned by * a NumberFormat factory method. * * @param pattern a non-localized pattern string * @param symbols the set of symbols to be used * @exception NullPointerException if any of the given arguments is null * @exception IllegalArgumentException if the given pattern is invalid * @see java.text.NumberFormat#getInstance * @see java.text.NumberFormat#getNumberInstance * @see java.text.NumberFormat#getCurrencyInstance * @see java.text.NumberFormat#getPercentInstance * @see java.text.DecimalFormatSymbols */ public DecimalFormat (String pattern, DecimalFormatSymbols symbols) { // Always applyPattern after the symbols are set this.symbols = (DecimalFormatSymbols)symbols.clone(); applyPattern(pattern, false); } // Overrides /** * Formats a number and appends the resulting text to the given string * buffer. * The number can be of any subclass of {@link java.lang.Number}. * <p> * This implementation uses the maximum precision permitted. * @param number the number to format * @param toAppendTo the <code>StringBuffer</code> to which the formatted * text is to be appended * @param pos On input: an alignment field, if desired. * On output: the offsets of the alignment field. * @return the value passed in as <code>toAppendTo</code> * @exception IllegalArgumentException if <code>number</code> is * null or not an instance of <code>Number</code>. * @exception NullPointerException if <code>toAppendTo</code> or * <code>pos</code> is null * @exception ArithmeticException if rounding is needed with rounding * mode being set to RoundingMode.UNNECESSARY * @see java.text.FieldPosition */ public final StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition pos) { if (number instanceof Long || number instanceof Integer || number instanceof Short || number instanceof Byte || number instanceof AtomicInteger || number instanceof AtomicLong || (number instanceof BigInteger && ((BigInteger)number).bitLength () < 64)) { return format(((Number)number).longValue(), toAppendTo, pos); } else if (number instanceof BigDecimal) { return format((BigDecimal)number, toAppendTo, pos); } else if (number instanceof BigInteger) {Lines 1–500 of 3278. Load more
/* * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved * * The original version of this source code and documentation is copyrighted * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These * materials are provided under terms of a License Agreement between Taligent * and Sun. This technology is protected by multiple US and International * patents. This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.text; import java.io.InvalidObjectException; import java.io.IOException; import java.io.ObjectInputStream; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Currency; import java.util.Locale; import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import sun.util.resources.LocaleData; /** * <code>DecimalFormat</code> is a concrete subclass of * <code>NumberFormat</code> that formats decimal numbers. It has a variety of * features designed to make it possible to parse and format numbers in any * locale, including support for Western, Arabic, and Indic digits. It also * supports different kinds of numbers, including integers (123), fixed-point * numbers (123.4), scientific notation (1.23E4), percentages (12%), and * currency amounts ($123). All of these can be localized. * * <p>To obtain a <code>NumberFormat</code> for a specific locale, including the * default locale, call one of <code>NumberFormat</code>'s factory methods, such * as <code>getInstance()</code>. In general, do not call the * <code>DecimalFormat</code> constructors directly, since the * <code>NumberFormat</code> factory methods may return subclasses other than * <code>DecimalFormat</code>. If you need to customize the format object, do * something like this: * * <blockquote><pre> * NumberFormat f = NumberFormat.getInstance(loc); * if (f instanceof DecimalFormat) { * ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true); * } * </pre></blockquote> * * <p>A <code>DecimalFormat</code> comprises a <em>pattern</em> and a set of * <em>symbols</em>. The pattern may be set directly using * <code>applyPattern()</code>, or indirectly using the API methods. The * symbols are stored in a <code>DecimalFormatSymbols</code> object. When using * the <code>NumberFormat</code> factory methods, the pattern and symbols are * read from localized <code>ResourceBundle</code>s. * * <h4>Patterns</h4> * * <code>DecimalFormat</code> patterns have the following syntax: * <blockquote><pre> * <i>Pattern:</i> * <i>PositivePattern</i> * <i>PositivePattern</i> ; <i>NegativePattern</i> * <i>PositivePattern:</i> * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i> * <i>NegativePattern:</i> * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i> * <i>Prefix:</i> * any Unicode characters except \uFFFE, \uFFFF, and special characters * <i>Suffix:</i> * any Unicode characters except \uFFFE, \uFFFF, and special characters * <i>Number:</i> * <i>Integer</i> <i>Exponent<sub>opt</sub></i> * <i>Integer</i> . <i>Fraction</i> <i>Exponent<sub>opt</sub></i> * <i>Integer:</i> * <i>MinimumInteger</i> * # * # <i>Integer</i> * # , <i>Integer</i> * <i>MinimumInteger:</i> * 0 * 0 <i>MinimumInteger</i> * 0 , <i>MinimumInteger</i> * <i>Fraction:</i> * <i>MinimumFraction<sub>opt</sub></i> <i>OptionalFraction<sub>opt</sub></i> * <i>MinimumFraction:</i> * 0 <i>MinimumFraction<sub>opt</sub></i> * <i>OptionalFraction:</i> * # <i>OptionalFraction<sub>opt</sub></i> * <i>Exponent:</i> * E <i>MinimumExponent</i> * <i>MinimumExponent:</i> * 0 <i>MinimumExponent<sub>opt</sub></i> * </pre></blockquote> * * <p>A <code>DecimalFormat</code> pattern contains a positive and negative * subpattern, for example, <code>"#,##0.00;(#,##0.00)"</code>. Each * subpattern has a prefix, numeric part, and suffix. The negative subpattern * is optional; if absent, then the positive subpattern prefixed with the * localized minus sign (<code>'-'</code> in most locales) is used as the * negative subpattern. That is, <code>"0.00"</code> alone is equivalent to * <code>"0.00;-0.00"</code>. If there is an explicit negative subpattern, it * serves only to specify the negative prefix and suffix; the number of digits, * minimal digits, and other characteristics are all the same as the positive * pattern. That means that <code>"#,##0.0#;(#)"</code> produces precisely * the same behavior as <code>"#,##0.0#;(#,##0.0#)"</code>. * * <p>The prefixes, suffixes, and various symbols used for infinity, digits, * thousands separators, decimal separators, etc. may be set to arbitrary * values, and they will appear properly during formatting. However, care must * be taken that the symbols and strings do not conflict, or parsing will be * unreliable. For example, either the positive and negative prefixes or the * suffixes must be distinct for <code>DecimalFormat.parse()</code> to be able * to distinguish positive from negative values. (If they are identical, then * <code>DecimalFormat</code> will behave as if no negative subpattern was * specified.) Another example is that the decimal separator and thousands * separator should be distinct characters, or parsing will be impossible. * * <p>The grouping separator is commonly used for thousands, but in some * countries it separates ten-thousands. The grouping size is a constant number * of digits between the grouping characters, such as 3 for 100,000,000 or 4 for * 1,0000,0000. If you supply a pattern with multiple grouping characters, the * interval between the last one and the end of the integer is the one that is * used. So <code>"#,##,###,####"</code> == <code>"######,####"</code> == * <code>"##,####,####"</code>. * * <h4>Special Pattern Characters</h4> * * <p>Many characters in a pattern are taken literally; they are matched during * parsing and output unchanged during formatting. Special characters, on the * other hand, stand for other characters, strings, or classes of characters. * They must be quoted, unless noted otherwise, if they are to appear in the * prefix or suffix as literals. * * <p>The characters listed here are used in non-localized patterns. Localized * patterns use the corresponding characters taken from this formatter's * <code>DecimalFormatSymbols</code> object instead, and these characters lose * their special status. Two exceptions are the currency sign and quote, which * are not localized. * * <blockquote> * <table border=0 cellspacing=3 cellpadding=0 summary="Chart showing symbol, * location, localized, and meaning."> * <tr bgcolor="#ccccff"> * <th align=left>Symbol * <th align=left>Location * <th align=left>Localized? * <th align=left>Meaning * <tr valign=top> * <td><code>0</code> * <td>Number * <td>Yes * <td>Digit * <tr valign=top bgcolor="#eeeeff"> * <td><code>#</code> * <td>Number * <td>Yes * <td>Digit, zero shows as absent * <tr valign=top> * <td><code>.</code> * <td>Number * <td>Yes * <td>Decimal separator or monetary decimal separator * <tr valign=top bgcolor="#eeeeff"> * <td><code>-</code> * <td>Number * <td>Yes * <td>Minus sign * <tr valign=top> * <td><code>,</code> * <td>Number * <td>Yes * <td>Grouping separator * <tr valign=top bgcolor="#eeeeff"> * <td><code>E</code> * <td>Number * <td>Yes * <td>Separates mantissa and exponent in scientific notation. * <em>Need not be quoted in prefix or suffix.</em> * <tr valign=top> * <td><code>;</code> * <td>Subpattern boundary * <td>Yes * <td>Separates positive and negative subpatterns * <tr valign=top bgcolor="#eeeeff"> * <td><code>%</code> * <td>Prefix or suffix * <td>Yes * <td>Multiply by 100 and show as percentage * <tr valign=top> * <td><code>\u2030</code> * <td>Prefix or suffix * <td>Yes * <td>Multiply by 1000 and show as per mille value * <tr valign=top bgcolor="#eeeeff"> * <td><code>¤</code> (<code>\u00A4</code>) * <td>Prefix or suffix * <td>No * <td>Currency sign, replaced by currency symbol. If * doubled, replaced by international currency symbol. * If present in a pattern, the monetary decimal separator * is used instead of the decimal separator. * <tr valign=top> * <td><code>'</code> * <td>Prefix or suffix * <td>No * <td>Used to quote special characters in a prefix or suffix, * for example, <code>"'#'#"</code> formats 123 to * <code>"#123"</code>. To create a single quote * itself, use two in a row: <code>"# o''clock"</code>. * </table> * </blockquote> * * <h4>Scientific Notation</h4> * * <p>Numbers in scientific notation are expressed as the product of a mantissa * and a power of ten, for example, 1234 can be expressed as 1.234 x 10^3. The * mantissa is often in the range 1.0 <= x < 10.0, but it need not be. * <code>DecimalFormat</code> can be instructed to format and parse scientific * notation <em>only via a pattern</em>; there is currently no factory method * that creates a scientific notation format. In a pattern, the exponent * character immediately followed by one or more digit characters indicates * scientific notation. Example: <code>"0.###E0"</code> formats the number * 1234 as <code>"1.234E3"</code>. * * <ul> * <li>The number of digit characters after the exponent character gives the * minimum exponent digit count. There is no maximum. Negative exponents are * formatted using the localized minus sign, <em>not</em> the prefix and suffix * from the pattern. This allows patterns such as <code>"0.###E0 m/s"</code>. * * <li>The minimum and maximum number of integer digits are interpreted * together: * * <ul> * <li>If the maximum number of integer digits is greater than their minimum number * and greater than 1, it forces the exponent to be a multiple of the maximum * number of integer digits, and the minimum number of integer digits to be * interpreted as 1. The most common use of this is to generate * <em>engineering notation</em>, in which the exponent is a multiple of three, * e.g., <code>"##0.#####E0"</code>. Using this pattern, the number 12345 * formats to <code>"12.345E3"</code>, and 123456 formats to * <code>"123.456E3"</code>. * * <li>Otherwise, the minimum number of integer digits is achieved by adjusting the * exponent. Example: 0.00123 formatted with <code>"00.###E0"</code> yields * <code>"12.3E-4"</code>. * </ul> * * <li>The number of significant digits in the mantissa is the sum of the * <em>minimum integer</em> and <em>maximum fraction</em> digits, and is * unaffected by the maximum integer digits. For example, 12345 formatted with * <code>"##0.##E0"</code> is <code>"12.3E3"</code>. To show all digits, set * the significant digits count to zero. The number of significant digits * does not affect parsing. * * <li>Exponential patterns may not contain grouping separators. * </ul> * * <h4>Rounding</h4> * * <code>DecimalFormat</code> provides rounding modes defined in * {@link java.math.RoundingMode} for formatting. By default, it uses * {@link java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}. * * <h4>Digits</h4> * * For formatting, <code>DecimalFormat</code> uses the ten consecutive * characters starting with the localized zero digit defined in the * <code>DecimalFormatSymbols</code> object as digits. For parsing, these * digits as well as all Unicode decimal digits, as defined by * {@link Character#digit Character.digit}, are recognized. * * <h4>Special Values</h4> * * <p><code>NaN</code> is formatted as a string, which typically has a single character * <code>\uFFFD</code>. This string is determined by the * <code>DecimalFormatSymbols</code> object. This is the only value for which * the prefixes and suffixes are not used. * * <p>Infinity is formatted as a string, which typically has a single character * <code>\u221E</code>, with the positive or negative prefixes and suffixes * applied. The infinity string is determined by the * <code>DecimalFormatSymbols</code> object. * * <p>Negative zero (<code>"-0"</code>) parses to * <ul> * <li><code>BigDecimal(0)</code> if <code>isParseBigDecimal()</code> is * true, * <li><code>Long(0)</code> if <code>isParseBigDecimal()</code> is false * and <code>isParseIntegerOnly()</code> is true, * <li><code>Double(-0.0)</code> if both <code>isParseBigDecimal()</code> * and <code>isParseIntegerOnly()</code> are false. * </ul> * * <h4><a name="synchronization">Synchronization</a></h4> * * <p> * Decimal formats are generally not synchronized. * It is recommended to create separate format instances for each thread. * If multiple threads access a format concurrently, it must be synchronized * externally. * * <h4>Example</h4> * * <blockquote><pre> * <strong>// Print out a number using the localized number, integer, currency, * // and percent format for each locale</strong> * Locale[] locales = NumberFormat.getAvailableLocales(); * double myNumber = -1234.56; * NumberFormat form; * for (int j=0; j<4; ++j) { * System.out.println("FORMAT"); * for (int i = 0; i < locales.length; ++i) { * if (locales[i].getCountry().length() == 0) { * continue; // Skip language-only locales * } * System.out.print(locales[i].getDisplayName()); * switch (j) { * case 0: * form = NumberFormat.getInstance(locales[i]); break; * case 1: * form = NumberFormat.getIntegerInstance(locales[i]); break; * case 2: * form = NumberFormat.getCurrencyInstance(locales[i]); break; * default: * form = NumberFormat.getPercentInstance(locales[i]); break; * } * if (form instanceof DecimalFormat) { * System.out.print(": " + ((DecimalFormat) form).toPattern()); * } * System.out.print(" -> " + form.format(myNumber)); * try { * System.out.println(" -> " + form.parse(form.format(myNumber))); * } catch (ParseException e) {} * } * } * </pre></blockquote> * * @see <a href="http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html">Java Tutorial</a> * @see NumberFormat * @see DecimalFormatSymbols * @see ParsePosition * @author Mark Davis * @author Alan Liu */ public class DecimalFormat extends NumberFormat { /** * Creates a DecimalFormat using the default pattern and symbols * for the default locale. This is a convenient way to obtain a * DecimalFormat when internationalization is not the main concern. * <p> * To obtain standard formats for a given locale, use the factory methods * on NumberFormat such as getNumberInstance. These factories will * return the most appropriate sub-class of NumberFormat for a given * locale. * * @see java.text.NumberFormat#getInstance * @see java.text.NumberFormat#getNumberInstance * @see java.text.NumberFormat#getCurrencyInstance * @see java.text.NumberFormat#getPercentInstance */ public DecimalFormat() { Locale def = Locale.getDefault(Locale.Category.FORMAT); // try to get the pattern from the cache String pattern = cachedLocaleData.get(def); if (pattern == null) { /* cache miss */ // Get the pattern for the default locale. ResourceBundle rb = LocaleData.getNumberFormatData(def); String[] all = rb.getStringArray("NumberPatterns"); pattern = all[0]; /* update cache */ cachedLocaleData.putIfAbsent(def, pattern); } // Always applyPattern after the symbols are set this.symbols = new DecimalFormatSymbols(def); applyPattern(pattern, false); } /** * Creates a DecimalFormat using the given pattern and the symbols * for the default locale. This is a convenient way to obtain a * DecimalFormat when internationalization is not the main concern. * <p> * To obtain standard formats for a given locale, use the factory methods * on NumberFormat such as getNumberInstance. These factories will * return the most appropriate sub-class of NumberFormat for a given * locale. * * @param pattern A non-localized pattern string. * @exception NullPointerException if <code>pattern</code> is null * @exception IllegalArgumentException if the given pattern is invalid. * @see java.text.NumberFormat#getInstance * @see java.text.NumberFormat#getNumberInstance * @see java.text.NumberFormat#getCurrencyInstance * @see java.text.NumberFormat#getPercentInstance */ public DecimalFormat(String pattern) { // Always applyPattern after the symbols are set this.symbols = new DecimalFormatSymbols(Locale.getDefault(Locale.Category.FORMAT)); applyPattern(pattern, false); } /** * Creates a DecimalFormat using the given pattern and symbols. * Use this constructor when you need to completely customize the * behavior of the format. * <p> * To obtain standard formats for a given * locale, use the factory methods on NumberFormat such as * getInstance or getCurrencyInstance. If you need only minor adjustments * to a standard format, you can modify the format returned by * a NumberFormat factory method. * * @param pattern a non-localized pattern string * @param symbols the set of symbols to be used * @exception NullPointerException if any of the given arguments is null * @exception IllegalArgumentException if the given pattern is invalid * @see java.text.NumberFormat#getInstance * @see java.text.NumberFormat#getNumberInstance * @see java.text.NumberFormat#getCurrencyInstance * @see java.text.NumberFormat#getPercentInstance * @see java.text.DecimalFormatSymbols */ public DecimalFormat (String pattern, DecimalFormatSymbols symbols) { // Always applyPattern after the symbols are set this.symbols = (DecimalFormatSymbols)symbols.clone(); applyPattern(pattern, false); } // Overrides /** * Formats a number and appends the resulting text to the given string * buffer. * The number can be of any subclass of {@link java.lang.Number}. * <p> * This implementation uses the maximum precision permitted. * @param number the number to format * @param toAppendTo the <code>StringBuffer</code> to which the formatted * text is to be appended * @param pos On input: an alignment field, if desired. * On output: the offsets of the alignment field. * @return the value passed in as <code>toAppendTo</code> * @exception IllegalArgumentException if <code>number</code> is * null or not an instance of <code>Number</code>. * @exception NullPointerException if <code>toAppendTo</code> or * <code>pos</code> is null * @exception ArithmeticException if rounding is needed with rounding * mode being set to RoundingMode.UNNECESSARY * @see java.text.FieldPosition */ public final StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition pos) { if (number instanceof Long || number instanceof Integer || number instanceof Short || number instanceof Byte || number instanceof AtomicInteger || number instanceof AtomicLong || (number instanceof BigInteger && ((BigInteger)number).bitLength () < 64)) { return format(((Number)number).longValue(), toAppendTo, pos); } else if (number instanceof BigDecimal) { return format((BigDecimal)number, toAppendTo, pos); } else if (number instanceof BigInteger) {