⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 decimalformat.java

📁 gcc的组建
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/* DecimalFormat.java -- Formats and parses numbers   Copyright (C) 1999, 2000, 2001, 2003, 2004, 2005  Free Software Foundation, Inc.This file is part of GNU Classpath.GNU Classpath is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2, or (at your option)any later version. GNU Classpath is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNUGeneral Public License for more details.You should have received a copy of the GNU General Public Licensealong with GNU Classpath; see the file COPYING.  If not, write to theFree Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA02110-1301 USA.Linking this library statically or dynamically with other modules ismaking a combined work based on this library.  Thus, the terms andconditions of the GNU General Public License cover the wholecombination.As a special exception, the copyright holders of this library give youpermission to link this library with independent modules to produce anexecutable, regardless of the license terms of these independentmodules, and to copy and distribute the resulting executable underterms of your choice, provided that you also meet, for each linkedindependent module, the terms and conditions of the license of thatmodule.  An independent module is a module which is not derived fromor based on this library.  If you modify this library, you may extendthis exception to your version of the library, but you are notobligated to do so.  If you do not wish to do so, delete thisexception statement from your version. */package java.text;import gnu.java.text.AttributedFormatBuffer;import gnu.java.text.FormatBuffer;import gnu.java.text.FormatCharacterIterator;import gnu.java.text.StringFormatBuffer;import java.io.IOException;import java.io.ObjectInputStream;import java.util.Currency;import java.util.HashMap;import java.util.Locale;/** * @author Tom Tromey (tromey@cygnus.com) * @author Andrew John Hughes (gnu_andrew@member.fsf.org) * @date March 4, 1999 *//* Written using "Java Class Libraries", 2nd edition, plus online * API docs for JDK 1.2 from http://www.javasoft.com. * Status:  Believed complete and correct to 1.2. * Note however that the docs are very unclear about how format parsing * should work.  No doubt there are problems here. */public class DecimalFormat extends NumberFormat{  // This is a helper for applyPatternWithSymbols.  It reads a prefix  // or a suffix.  It can cause some side-effects.  private int scanFix (String pattern, int index, FormatBuffer buf,                       String patChars, DecimalFormatSymbols syms,                       boolean is_suffix)    {    int len = pattern.length();    boolean quoteStarted = false;    buf.clear();        boolean multiplierSet = false;    while (index < len)      {	char c = pattern.charAt(index);	if (quoteStarted)	  {	    if (c == '\'')	      quoteStarted = false;	    else	      buf.append(c);	    index++;	    continue;	  }	if (c == '\'' && index + 1 < len	    && pattern.charAt(index + 1) == '\'')	  {	    buf.append(c);	    index++;	  }	else if (c == '\'')	  {	    quoteStarted = true;	  }	else if (c == '\u00a4')	  {			/* Currency interpreted later */			buf.append(c);		}	else if (c == syms.getPercent())	  {	    if (multiplierSet)	      throw new IllegalArgumentException ("multiplier already set " +						  "- index: " + index);	    multiplierSet = true;	    multiplier = 100;	    buf.append(c, NumberFormat.Field.PERCENT);	  }	else if (c == syms.getPerMill())	  {	    if (multiplierSet)	      throw new IllegalArgumentException ("multiplier already set " +						  "- index: " + index);	    multiplierSet = true;	    multiplier = 1000;	    buf.append(c, NumberFormat.Field.PERMILLE);	  }	else if (patChars.indexOf(c) != -1)	  {	    // This is a pattern character.	    break;	  }	else		{			buf.append(c);		}	index++;      }    if (quoteStarted)      throw new IllegalArgumentException ("pattern is lacking a closing quote");    return index;  }  // A helper which reads a number format.  private int scanFormat (String pattern, int index, String patChars,                          DecimalFormatSymbols syms, boolean is_positive)  {    int max = pattern.length();    int countSinceGroup = 0;    int zeroCount = 0;    boolean saw_group = false;    //    // Scan integer part.    //    while (index < max)      {	char c = pattern.charAt(index);	if (c == syms.getDigit())	  {	    if (zeroCount > 0)	      throw new IllegalArgumentException ("digit mark following " +						  "zero - index: " + index);	    ++countSinceGroup;	  }	else if (c == syms.getZeroDigit())	  {	    ++zeroCount;	    ++countSinceGroup;	  }	else if (c == syms.getGroupingSeparator())	  {	    countSinceGroup = 0;	    saw_group = true;	  }	else	  break;	++index;      }    // We can only side-effect when parsing the positive format.    if (is_positive)      {	groupingUsed = saw_group;	groupingSize = (byte) countSinceGroup;	// Checking "zeroCount > 0" avoids 0 being formatted into "" with "#".	if (zeroCount > 0)	  minimumIntegerDigits = zeroCount;      }    // Early termination.    if (index == max || pattern.charAt(index) == syms.getGroupingSeparator())      {	if (is_positive)	  decimalSeparatorAlwaysShown = false;	return index;      }    if (pattern.charAt(index) == syms.getDecimalSeparator())      {	++index;	//	// Scan fractional part.	//	int hashCount = 0;	zeroCount = 0;	while (index < max)	  {	    char c = pattern.charAt(index);	    if (c == syms.getZeroDigit())	      {		if (hashCount > 0)		  throw new IllegalArgumentException ("zero mark " +						      "following digit - index: " + index);		++zeroCount;	      }	    else if (c == syms.getDigit())	      {		++hashCount;	      }	    else if (c != syms.getExponential()		     && c != syms.getPatternSeparator()		     && c != syms.getPercent()		     && c != syms.getPerMill()		     && patChars.indexOf(c) != -1)	      throw new IllegalArgumentException ("unexpected special " +						  "character - index: " + index);	    else	      break;	    ++index;	  }	if (is_positive)	  {	    maximumFractionDigits = hashCount + zeroCount;	    minimumFractionDigits = zeroCount;	  }	if (index == max)	  return index;      }    if (pattern.charAt(index) == syms.getExponential())      {	//	// Scan exponential format.	//	zeroCount = 0;	++index;	while (index < max)	  {	    char c = pattern.charAt(index);	    if (c == syms.getZeroDigit())	      ++zeroCount;	    else if (c == syms.getDigit())	      {		if (zeroCount > 0)		  throw new		    IllegalArgumentException ("digit mark following zero " +					      "in exponent - index: " +					      index);	      }	    else if (patChars.indexOf(c) != -1)	      throw new IllegalArgumentException ("unexpected special " +						  "character - index: " +						  index);	    else	      break;	    ++index;	  }	if (is_positive)	  {	    useExponentialNotation = true;	    minExponentDigits = (byte) zeroCount;	  }	maximumIntegerDigits = groupingSize;	groupingSize = 0;	if (maximumIntegerDigits > minimumIntegerDigits && maximumIntegerDigits > 0)	  {	    minimumIntegerDigits = 1;	    exponentRound = maximumIntegerDigits;	  }	else	  exponentRound = 1;      }    return index;  }  // This helper function creates a string consisting of all the  // characters which can appear in a pattern and must be quoted.  private String patternChars (DecimalFormatSymbols syms)  {    StringBuffer buf = new StringBuffer ();    buf.append(syms.getDecimalSeparator());    buf.append(syms.getDigit());    buf.append(syms.getExponential());    buf.append(syms.getGroupingSeparator());    // Adding this one causes pattern application to fail.    // Of course, omitting is causes toPattern to fail.    // ... but we already have bugs there.  FIXME.    // buf.append(syms.getMinusSign());    buf.append(syms.getPatternSeparator());    buf.append(syms.getPercent());    buf.append(syms.getPerMill());    buf.append(syms.getZeroDigit());    buf.append('\u00a4');    return buf.toString();  }  private void applyPatternWithSymbols(String pattern, DecimalFormatSymbols syms)  {    // Initialize to the state the parser expects.    negativePrefix = "";    negativeSuffix = "";    positivePrefix = "";    positiveSuffix = "";    decimalSeparatorAlwaysShown = false;    groupingSize = 0;    minExponentDigits = 0;    multiplier = 1;    useExponentialNotation = false;    groupingUsed = false;    maximumFractionDigits = 0;    maximumIntegerDigits = MAXIMUM_INTEGER_DIGITS;    minimumFractionDigits = 0;    minimumIntegerDigits = 1;    AttributedFormatBuffer buf = new AttributedFormatBuffer ();    String patChars = patternChars (syms);    int max = pattern.length();    int index = scanFix (pattern, 0, buf, patChars, syms, false);    buf.sync();    positivePrefix = buf.getBuffer().toString();    positivePrefixRanges = buf.getRanges();    positivePrefixAttrs = buf.getAttributes();    index = scanFormat (pattern, index, patChars, syms, true);    index = scanFix (pattern, index, buf, patChars, syms, true);    buf.sync();    positiveSuffix = buf.getBuffer().toString();    positiveSuffixRanges = buf.getRanges();    positiveSuffixAttrs = buf.getAttributes();    if (index == pattern.length())      {	// No negative info.	negativePrefix = null;	negativeSuffix = null;      }    else      {	if (pattern.charAt(index) != syms.getPatternSeparator())	  throw new IllegalArgumentException ("separator character " +					      "expected - index: " + index);	index = scanFix (pattern, index + 1, buf, patChars, syms, false);	buf.sync();	negativePrefix = buf.getBuffer().toString();	negativePrefixRanges = buf.getRanges();	negativePrefixAttrs = buf.getAttributes();	// We parse the negative format for errors but we don't let	// it side-effect this object.	index = scanFormat (pattern, index, patChars, syms, false);	index = scanFix (pattern, index, buf, patChars, syms, true);	buf.sync();	negativeSuffix = buf.getBuffer().toString();	negativeSuffixRanges = buf.getRanges();	negativeSuffixAttrs = buf.getAttributes();	if (index != pattern.length())	  throw new IllegalArgumentException ("end of pattern expected " +					      "- index: " + index);      }  }  public void applyLocalizedPattern (String pattern)  {    // JCL p. 638 claims this throws a ParseException but p. 629    // contradicts this.  Empirical tests with patterns of "0,###.0"    // and "#.#.#" corroborate the p. 629 statement that an    // IllegalArgumentException is thrown.    applyPatternWithSymbols (pattern, symbols);  }  public void applyPattern (String pattern)  {    // JCL p. 638 claims this throws a ParseException but p. 629    // contradicts this.  Empirical tests with patterns of "0,###.0"    // and "#.#.#" corroborate the p. 629 statement that an    // IllegalArgumentException is thrown.    applyPatternWithSymbols (pattern, nonLocalizedSymbols);  }  public Object clone ()  {    DecimalFormat c = (DecimalFormat) super.clone ();    c.symbols = (DecimalFormatSymbols) symbols.clone ();    return c;  }  /**   * Constructs a <code>DecimalFormat</code> which uses the default   * pattern and symbols.   */  public DecimalFormat ()  {    this ("#,##0.###");  }  /**   * Constructs a <code>DecimalFormat</code> which uses the given   * pattern and the default symbols for formatting and parsing.   *   * @param pattern the non-localized pattern to use.   * @throws NullPointerException if any argument is null.   * @throws IllegalArgumentException if the pattern is invalid.   */  public DecimalFormat (String pattern)  {    this (pattern, new DecimalFormatSymbols ());  }  /**   * Constructs a <code>DecimalFormat</code> using the given pattern   * and formatting symbols.  This construction method is used to give   * complete control over the formatting process.     *   * @param pattern the non-localized pattern to use.   * @param symbols the set of symbols used for parsing and formatting.   * @throws NullPointerException if any argument is null.   * @throws IllegalArgumentException if the pattern is invalid.   */  public DecimalFormat(String pattern, DecimalFormatSymbols symbols)  {    this.symbols = (DecimalFormatSymbols) symbols.clone();    applyPattern(pattern);  }  private boolean equals(String s1, String s2)  {    if (s1 == null || s2 == null)      return s1 == s2;    return s1.equals(s2);  }  /**   * Tests this instance for equality with an arbitrary object.  This method   * returns <code>true</code> if:   * <ul>   * <li><code>obj</code> is not <code>null</code>;</li>   * <li><code>obj</code> is an instance of <code>DecimalFormat</code>;</li>   * <li>this instance and <code>obj</code> have the same attributes;</li>   * </ul>   *    * @param obj  the object (<code>null</code> permitted).   *    * @return A boolean.   */  public boolean equals(Object obj)  {    if (! (obj instanceof DecimalFormat))      return false;    DecimalFormat dup = (DecimalFormat) obj;    return (decimalSeparatorAlwaysShown == dup.decimalSeparatorAlwaysShown            && groupingUsed == dup.groupingUsed            && groupingSize == dup.groupingSize            && multiplier == dup.multiplier           && useExponentialNotation == dup.useExponentialNotation           && minExponentDigits == dup.minExponentDigits           && minimumIntegerDigits == dup.minimumIntegerDigits           && maximumIntegerDigits == dup.maximumIntegerDigits

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -