DecimalFormat.java 68.6 KB
Newer Older
Tom Tromey committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/* 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 modify
it under the terms of the GNU General Public License as published by
the 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, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

38 39 40 41 42 43
/* 
 * This class contains few bits from ICU4J (http://icu.sourceforge.net/),
 * Copyright by IBM and others and distributed under the
 * distributed under MIT/X.
 */

Tom Tromey committed
44 45
package java.text;

46 47
import java.math.BigDecimal;
import java.math.BigInteger;
Tom Tromey committed
48

49
import java.util.ArrayList;
Tom Tromey committed
50 51 52
import java.util.Currency;
import java.util.Locale;

53 54 55 56
/*
 * This note is here for historical reasons and because I had not the courage
 * to remove it :)
 *  
Tom Tromey committed
57 58 59
 * @author Tom Tromey (tromey@cygnus.com)
 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
 * @date March 4, 1999
60 61
 *
 * Written using "Java Class Libraries", 2nd edition, plus online
Tom Tromey committed
62 63 64 65 66
 * 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.
 */
67 68 69 70 71 72 73 74 75 76 77

/**
 * This class is a concrete implementation of NumberFormat used to format
 * decimal numbers. The class can format numbers given a specific locale.
 * Generally, to get an instance of DecimalFormat you should call the factory
 * methods in the <code>NumberFormat</code> base class.
 * 
 * @author Mario Torre <neugens@limasoftware.net>
 * @author Tom Tromey (tromey@cygnus.com)
 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
 */
Tom Tromey committed
78 79
public class DecimalFormat extends NumberFormat
{
80 81 82 83 84
  /** serialVersionUID for serializartion. */
  private static final long serialVersionUID = 864413376551465018L;
  
  /** Defines the default number of digits allowed while formatting integers. */
  private static final int DEFAULT_INTEGER_DIGITS = 309; 
Tom Tromey committed
85 86

  /**
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
   * Defines the default number of digits allowed while formatting
   * fractions.
   */
  private static final int DEFAULT_FRACTION_DIGITS = 340;
  
  /**
   * Locale-independent pattern symbols.
   */
  // Happen to be the same as the US symbols.
  private static final DecimalFormatSymbols nonLocalizedSymbols
    = new DecimalFormatSymbols (Locale.US);
  
  /**
   * Defines if parse should return a BigDecimal or not.
   */
  private boolean parseBigDecimal;
  
  /**
   * Defines if we have to use the monetary decimal separator or
   * the decimal separator while formatting numbers.
   */
  private boolean useCurrencySeparator;
    
  /** Defines if the decimal separator is always shown or not. */
  private boolean decimalSeparatorAlwaysShown;
  
  /**
   * Defines if the decimal separator has to be shown.
   * 
   * This is different then <code>decimalSeparatorAlwaysShown</code>,
   * as it defines if the format string contains a decimal separator or no.
   */
  private boolean showDecimalSeparator;
  
  /**
   * This field is used to determine if the grouping
   * separator is included in the format string or not.
   * This is only needed to match the behaviour of the RI.
   */
  private boolean groupingSeparatorInPattern;
  
  /** Defines the size of grouping groups when grouping is used. */
  private byte groupingSize;
  
  /**
   * This is an internal parameter used to keep track of the number
   * of digits the form the exponent, when exponential notation is used.
   * It is used with <code>exponentRound</code>
   */
  private byte minExponentDigits;
 
  /** This field is used to set the exponent in the engineering notation. */
  private int exponentRound;
  
  /** Multiplier used in percent style formats. */
  private int multiplier;
  
  /** Multiplier used in percent style formats. */
  private int negativePatternMultiplier;
  
  /** The negative prefix. */
  private String negativePrefix;
  
  /** The negative suffix. */
  private String negativeSuffix;
  
  /** The positive prefix. */
  private String positivePrefix;
  
  /** The positive suffix. */
  private String positiveSuffix;
  
  /** Decimal Format Symbols for the given locale. */
  private DecimalFormatSymbols symbols;
  
  /** Determine if we have to use exponential notation or not. */
  private boolean useExponentialNotation;
  
  /**
   * Defines the maximum number of integer digits to show when we use
   * the exponential notation.
   */
  private int maxIntegerDigitsExponent;
  
  /** Defines if the format string has a negative prefix or not. */
  private boolean hasNegativePrefix;
  
  /** Defines if the format string has a fractional pattern or not. */
  private boolean hasFractionalPattern;
 
  /** Stores a list of attributes for use by formatToCharacterIterator. */
  private ArrayList attributes = new ArrayList();
  
  /**
Tom Tromey committed
181 182 183
   * Constructs a <code>DecimalFormat</code> which uses the default
   * pattern and symbols.
   */
184
  public DecimalFormat()
Tom Tromey committed
185 186 187
  {
    this ("#,##0.###");
  }
188
  
Tom Tromey committed
189 190 191 192 193 194 195 196
  /**
   * 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.
   */
197
  public DecimalFormat(String pattern)
Tom Tromey committed
198
  {
199
    this (pattern, new DecimalFormatSymbols());
Tom Tromey committed
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
  }

  /**
   * 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();
215 216 217 218 219 220 221 222 223 224 225 226 227
    applyPatternWithSymbols(pattern, nonLocalizedSymbols);
  }
  
  /**
   * Apply the given localized patern to the current DecimalFormat object.
   * 
   * @param pattern The localized pattern to apply.
   * @throws IllegalArgumentException if the given pattern is invalid.
   * @throws NullPointerException if the input pattern is null.
   */
  public void applyLocalizedPattern (String pattern)
  {
    applyPatternWithSymbols(pattern, this.symbols);
Tom Tromey committed
228 229
  }

230 231 232 233 234 235 236 237
  /**
   * Apply the given localized pattern to the current DecimalFormat object.
   * 
   * @param pattern The localized pattern to apply.
   * @throws IllegalArgumentException if the given pattern is invalid.
   * @throws NullPointerException if the input pattern is null.
   */
  public void applyPattern(String pattern)
Tom Tromey committed
238
  {
239 240 241 242 243 244 245 246
    applyPatternWithSymbols(pattern, nonLocalizedSymbols);
  }

  public Object clone()
  {
    DecimalFormat c = (DecimalFormat) super.clone();
    c.symbols = (DecimalFormatSymbols) symbols.clone();
    return c;
Tom Tromey committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
  }

  /**
   * 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 
268 269 270
           && groupingUsed == dup.groupingUsed
           && groupingSeparatorInPattern == dup.groupingSeparatorInPattern 
           && groupingSize == dup.groupingSize
Tom Tromey committed
271 272 273 274 275 276 277
           && multiplier == dup.multiplier
           && useExponentialNotation == dup.useExponentialNotation
           && minExponentDigits == dup.minExponentDigits
           && minimumIntegerDigits == dup.minimumIntegerDigits
           && maximumIntegerDigits == dup.maximumIntegerDigits
           && minimumFractionDigits == dup.minimumFractionDigits
           && maximumFractionDigits == dup.maximumFractionDigits
278 279 280 281 282 283 284 285
           && parseBigDecimal == dup.parseBigDecimal
           && useCurrencySeparator == dup.useCurrencySeparator
           && showDecimalSeparator == dup.showDecimalSeparator
           && exponentRound == dup.exponentRound
           && negativePatternMultiplier == dup.negativePatternMultiplier
           && maxIntegerDigitsExponent == dup.maxIntegerDigitsExponent
           // XXX: causes equivalent patterns to fail
           // && hasNegativePrefix == dup.hasNegativePrefix
Tom Tromey committed
286 287 288 289 290 291 292
           && equals(negativePrefix, dup.negativePrefix)
           && equals(negativeSuffix, dup.negativeSuffix)
           && equals(positivePrefix, dup.positivePrefix)
           && equals(positiveSuffix, dup.positiveSuffix)
           && symbols.equals(dup.symbols));
  }

293 294 295 296 297 298
  /**
   * Returns a hash code for this object.
   *
   * @return A hash code.
   */
  public int hashCode()
Tom Tromey committed
299
  {
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    return toPattern().hashCode();
  }
  
  /**
   * Produce a formatted {@link String} representation of this object.
   * The passed object must be of type number. 
   * 
   * @param obj The {@link Number} to format.
   * @param sbuf The destination String; text will be appended to this String. 
   * @param pos If used on input can be used to define an alignment
   * field. If used on output defines the offsets of the alignment field.
   * @return The String representation of this long.
   */
  public StringBuffer format(Object obj, StringBuffer sbuf, FieldPosition pos)
  {
    if (obj instanceof BigInteger)
Tom Tromey committed
316
      {
317 318 319
        BigDecimal decimal = new BigDecimal((BigInteger) obj);
        formatInternal(decimal, true, sbuf, pos);
        return sbuf;
Tom Tromey committed
320
      }
321
    else if (obj instanceof BigDecimal)
Tom Tromey committed
322
      {
323 324
        formatInternal((BigDecimal) obj, true, sbuf, pos);
        return sbuf;
Tom Tromey committed
325
      }
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    
    return super.format(obj, sbuf, pos);
  }
  
  /**
   * Produce a formatted {@link String} representation of this double.
   * 
   * @param number The double to format.
   * @param dest The destination String; text will be appended to this String. 
   * @param fieldPos If used on input can be used to define an alignment
   * field. If used on output defines the offsets of the alignment field.
   * @return The String representation of this long.
   * @throws NullPointerException if <code>dest</code> or fieldPos are null
   */
  public StringBuffer format(double number, StringBuffer dest,
			     FieldPosition fieldPos)
  {
    // special cases for double: NaN and negative or positive infinity
    if (Double.isNaN(number))
Tom Tromey committed
345
      {
346 347 348 349 350 351 352 353 354 355 356 357
        // 1. NaN
        String nan = symbols.getNaN();
        dest.append(nan);
        
        // update field position if required
        if ((fieldPos.getField() == INTEGER_FIELD ||
             fieldPos.getFieldAttribute() == NumberFormat.Field.INTEGER))
          {
            int index = dest.length();
            fieldPos.setBeginIndex(index - nan.length());
            fieldPos.setEndIndex(index);
          }
Tom Tromey committed
358
      }
359
    else if (Double.isInfinite(number))
Tom Tromey committed
360
      {
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
        // 2. Infinity
        if (number < 0)
          dest.append(this.negativePrefix);
        else
          dest.append(this.positivePrefix);
        
        dest.append(symbols.getInfinity());
        
        if (number < 0)
          dest.append(this.negativeSuffix);
        else
          dest.append(this.positiveSuffix);
        
        if ((fieldPos.getField() == INTEGER_FIELD ||
            fieldPos.getFieldAttribute() == NumberFormat.Field.INTEGER))
         {
           fieldPos.setBeginIndex(dest.length());
           fieldPos.setEndIndex(0);
         }
Tom Tromey committed
380 381 382
      }
    else
      {
383 384 385
        // get the number as a BigDecimal
        BigDecimal bigDecimal = new BigDecimal(String.valueOf(number));
        formatInternal(bigDecimal, false, dest, fieldPos);
Tom Tromey committed
386
      }
387 388
    
    return dest;
Tom Tromey committed
389 390
  }

391 392 393 394 395 396 397 398 399 400 401
  /**
   * Produce a formatted {@link String} representation of this long.
   * 
   * @param number The long to format.
   * @param dest The destination String; text will be appended to this String. 
   * @param fieldPos If used on input can be used to define an alignment
   * field. If used on output defines the offsets of the alignment field.
   * @return The String representation of this long.
   */
  public StringBuffer format(long number, StringBuffer dest,
                             FieldPosition fieldPos)
Tom Tromey committed
402
  {
403 404
    BigDecimal bigDecimal = new BigDecimal(String.valueOf(number));
    formatInternal(bigDecimal, true, dest, fieldPos);
Tom Tromey committed
405 406
    return dest;
  }
407 408 409 410 411 412 413 414 415 416 417
  
  /**
   * Return an <code>AttributedCharacterIterator</code> as a result of
   * the formatting of the passed {@link Object}.
   * 
   * @return An {@link AttributedCharacterIterator}.
   * @throws NullPointerException if value is <code>null</code>. 
   * @throws IllegalArgumentException if value is not an instance of
   * {@link Number}.
   */
  public AttributedCharacterIterator formatToCharacterIterator(Object value)
Tom Tromey committed
418
  {
419 420 421 422
    /*
     * This method implementation derives directly from the
     * ICU4J (http://icu.sourceforge.net/) library, distributed under MIT/X.
     */
Tom Tromey committed
423
    
424 425 426 427 428 429 430 431 432
    if (value == null)
      throw new NullPointerException("Passed Object is null");
    
    if (!(value instanceof Number)) throw new
      IllegalArgumentException("Cannot format given Object as a Number");
    
    StringBuffer text = new StringBuffer();
    attributes.clear();
    super.format(value, text, new FieldPosition(0));
Tom Tromey committed
433

434
    AttributedString as = new AttributedString(text.toString());
Tom Tromey committed
435

436 437
    // add NumberFormat field attributes to the AttributedString
    for (int i = 0; i < attributes.size(); i++)
Tom Tromey committed
438
      {
439 440 441
        FieldPosition pos = (FieldPosition) attributes.get(i);
        Format.Field attribute = pos.getFieldAttribute();
        
442 443
        as.addAttribute(attribute, attribute, pos.getBeginIndex(),
                        pos.getEndIndex());
Tom Tromey committed
444
      }
445 446 447
    
    // return the CharacterIterator from AttributedString
    return as.getIterator();
Tom Tromey committed
448
  }
449
  
Tom Tromey committed
450 451 452 453 454 455 456 457 458 459 460 461
  /**
   * Returns the currency corresponding to the currency symbol stored
   * in the instance of <code>DecimalFormatSymbols</code> used by this
   * <code>DecimalFormat</code>.
   *
   * @return A new instance of <code>Currency</code> if
   * the currency code matches a known one, null otherwise.
   */
  public Currency getCurrency()
  {
    return symbols.getCurrency();
  }
462
  
Tom Tromey committed
463 464 465 466 467 468 469 470 471
  /**
   * Returns a copy of the symbols used by this instance.
   * 
   * @return A copy of the symbols.
   */
  public DecimalFormatSymbols getDecimalFormatSymbols()
  {
    return (DecimalFormatSymbols) symbols.clone();
  }
472 473 474 475 476 477 478 479 480 481 482 483
  
  /**
   * Gets the interval used between a grouping separator and the next.
   * For example, a grouping size of 3 means that the number 1234 is
   * formatted as 1,234.
   * 
   * The actual character used as grouping separator depends on the
   * locale and is defined by {@link DecimalFormatSymbols#getDecimalSeparator()}
   * 
   * @return The interval used between a grouping separator and the next.
   */
  public int getGroupingSize()
Tom Tromey committed
484 485 486 487
  {
    return groupingSize;
  }

488 489 490 491 492 493
  /**
   * Gets the multiplier used in percent and similar formats.
   * 
   * @return The multiplier used in percent and similar formats.
   */
  public int getMultiplier()
Tom Tromey committed
494 495 496
  {
    return multiplier;
  }
497 498 499 500 501 502 503
  
  /**
   * Gets the negative prefix.
   * 
   * @return The negative prefix.
   */
  public String getNegativePrefix()
Tom Tromey committed
504 505 506 507
  {
    return negativePrefix;
  }

508 509 510 511 512 513
  /**
   * Gets the negative suffix.
   * 
   * @return The negative suffix.
   */
  public String getNegativeSuffix()
Tom Tromey committed
514 515 516
  {
    return negativeSuffix;
  }
517 518 519 520 521 522 523
  
  /**
   * Gets the positive prefix.
   * 
   * @return The positive prefix.
   */
  public String getPositivePrefix()
Tom Tromey committed
524 525 526
  {
    return positivePrefix;
  }
527 528 529 530 531 532 533
  
  /**
   * Gets the positive suffix.
   *  
   * @return The positive suffix.
   */
  public String getPositiveSuffix()
Tom Tromey committed
534 535 536
  {
    return positiveSuffix;
  }
537 538 539 540 541 542
  
  public boolean isDecimalSeparatorAlwaysShown()
  {
    return decimalSeparatorAlwaysShown;
  }
  
Tom Tromey committed
543
  /**
544 545 546 547
   * Define if <code>parse(java.lang.String, java.text.ParsePosition)</code>
   * should return a {@link BigDecimal} or not. 
   * 
   * @param newValue
Tom Tromey committed
548
   */
549
  public void setParseBigDecimal(boolean newValue)
Tom Tromey committed
550
  {
551
    this.parseBigDecimal = newValue;
Tom Tromey committed
552
  }
553 554 555 556 557 558 559 560 561 562 563 564 565
  
  /**
   * Returns <code>true</code> if
   * <code>parse(java.lang.String, java.text.ParsePosition)</code> returns
   * a <code>BigDecimal</code>, <code>false</code> otherwise.
   * The default return value for this method is <code>false</code>.
   * 
   * @return <code>true</code> if the parse method returns a {@link BigDecimal},
   * <code>false</code> otherwise.
   * @since 1.5
   * @see #setParseBigDecimal(boolean)
   */
  public boolean isParseBigDecimal()
Tom Tromey committed
566
  {
567
    return this.parseBigDecimal;
Tom Tromey committed
568
  }
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
  
  /**
   * This method parses the specified string into a <code>Number</code>.
   * 
   * The parsing starts at <code>pos</code>, which is updated as the parser
   * consume characters in the passed string.
   * On error, the <code>Position</code> object index is not updated, while
   * error position is set appropriately, an <code>null</code> is returned.
   * 
   * @param str The string to parse.
   * @param pos The desired <code>ParsePosition</code>.
   *
   * @return The parsed <code>Number</code>
   */
  public Number parse(String str, ParsePosition pos)
Tom Tromey committed
584
  {
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
    // a special values before anything else
    // NaN
    if (str.contains(this.symbols.getNaN()))
      return Double.valueOf(Double.NaN);
   
    // this will be our final number
    StringBuffer number = new StringBuffer();
    
    // special character
    char minus = symbols.getMinusSign();
    
    // starting parsing position
    int start = pos.getIndex();
    
    // validate the string, it have to be in the 
    // same form as the format string or parsing will fail
    String _negativePrefix = (this.negativePrefix.compareTo("") == 0
                              ? minus + positivePrefix
                              : this.negativePrefix);
    
    // we check both prefixes, because one might be empty.
    // We want to pick the longest prefix that matches.
    int positiveLen = positivePrefix.length();
    int negativeLen = _negativePrefix.length();
    
    boolean isNegative = str.startsWith(_negativePrefix);
    boolean isPositive = str.startsWith(positivePrefix);
    
    if (isPositive && isNegative)
      {
        // By checking this way, we preserve ambiguity in the case
        // where the negative format differs only in suffix.
        if (negativeLen > positiveLen)
          {
            start += _negativePrefix.length();
            isNegative = true;
          }
        else
          {
            start += positivePrefix.length();
            isPositive = true;
            if (negativeLen < positiveLen)
              isNegative = false;
          }
      }
    else if (isNegative)
Tom Tromey committed
631
      {
632 633
        start += _negativePrefix.length();
        isPositive = false;
Tom Tromey committed
634
      }
635
    else if (isPositive)
Tom Tromey committed
636
      {
637 638
        start += positivePrefix.length();
        isNegative = false;
Tom Tromey committed
639 640 641
      }
    else
      {
642 643
        pos.setErrorIndex(start);
        return null;
Tom Tromey committed
644
      }
645 646 647 648 649 650 651 652
    
    // other special characters used by the parser
    char decimalSeparator = symbols.getDecimalSeparator();
    char zero = symbols.getZeroDigit();
    char exponent = symbols.getExponential(); 
    
    // stop parsing position in the string
    int stop = start + this.maximumIntegerDigits + maximumFractionDigits + 2;
Tom Tromey committed
653 654
    
    if (useExponentialNotation)
655 656 657
      stop += minExponentDigits + 1;
    
    boolean inExponent = false;
Tom Tromey committed
658

659 660 661
    // correct the size of the end parsing flag
    int len = str.length();
    if (len < stop) stop = len;
662
    char groupingSeparator = symbols.getGroupingSeparator();
663 664 665
    
    int i = start;
    while (i < stop)
Tom Tromey committed
666
      {
667 668 669 670 671 672 673 674 675
        char ch = str.charAt(i);
        i++;
       
        if (ch >= zero && ch <= (zero + 9))
          {
            number.append(ch);
          }
        else if (this.parseIntegerOnly)
          {
676
            i--;
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
            break;
          }
        else if (ch == decimalSeparator)
          {
            number.append('.');
          }
        else if (ch == exponent)
          {
            number.append(ch);
            inExponent = !inExponent;
          }
        else if ((ch == '+' || ch == '-' || ch == minus))
          {
            if (inExponent)
              number.append(ch);
            else
693 694 695 696
	      {
		i--;
        	break;
	      }
697
          }
698 699 700 701 702 703 704 705
	else
	  {
	    if (!groupingUsed || ch != groupingSeparator)
	      {
	        i--;
	        break;
	      }
	  }
Tom Tromey committed
706 707
      }

708 709 710
    // 2nd special case: infinity
    // XXX: need to be tested
    if (str.contains(symbols.getInfinity()))
Tom Tromey committed
711
      {
712 713 714 715 716 717 718 719 720 721 722 723 724 725
        int inf = str.indexOf(symbols.getInfinity()); 
        pos.setIndex(inf);
        
        // FIXME: ouch, this is really ugly and lazy code...
        if (this.parseBigDecimal)
          {
            if (isNegative)
              return new BigDecimal(Double.NEGATIVE_INFINITY);
            
            return new BigDecimal(Double.POSITIVE_INFINITY);
          }
        
        if (isNegative)
          return new Double(Double.NEGATIVE_INFINITY);
Tom Tromey committed
726

727
        return new Double(Double.POSITIVE_INFINITY);
Tom Tromey committed
728
      }
729 730 731
    
    // no number...
    if (i == start || number.length() == 0)
Tom Tromey committed
732
      {
733 734
        pos.setErrorIndex(i);
        return null;
Tom Tromey committed
735 736
      }

737 738
    // now we have to check the suffix, done here after number parsing
    // or the index will not be updated correctly...
739 740
    boolean hasNegativeSuffix = str.endsWith(this.negativeSuffix);
    boolean hasPositiveSuffix = str.endsWith(this.positiveSuffix);
741
    boolean positiveEqualsNegative = negativeSuffix.equals(positiveSuffix);
Tom Tromey committed
742

743 744 745
    positiveLen = positiveSuffix.length();
    negativeLen = negativeSuffix.length();
    
746
    if (isNegative && !hasNegativeSuffix)
Tom Tromey committed
747
      {
748 749
        pos.setErrorIndex(i);
        return null;
Tom Tromey committed
750
      }
751
    else if (hasNegativeSuffix &&
752 753
             !positiveEqualsNegative &&
             (negativeLen > positiveLen))
Tom Tromey committed
754
      {
755
        isNegative = true;
Tom Tromey committed
756
      }
757
    else if (!hasPositiveSuffix)
Tom Tromey committed
758
      {
759 760
        pos.setErrorIndex(i);
        return null;
Tom Tromey committed
761
      }
762 763 764
    
    if (isNegative) number.insert(0, '-');
   
765
    pos.setIndex(i);
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
    
    // now we handle the return type
    BigDecimal bigDecimal = new BigDecimal(number.toString());
    if (this.parseBigDecimal)
      return bigDecimal;
    
    // want integer?
    if (this.parseIntegerOnly)
      return new Long(bigDecimal.longValue());

    // 3th special case -0.0
    if (isNegative && (bigDecimal.compareTo(BigDecimal.ZERO) == 0))
      return new Double(-0.0);
    
    try
Tom Tromey committed
781
      {
782 783 784
        BigDecimal integer
          = bigDecimal.setScale(0, BigDecimal.ROUND_UNNECESSARY);
        return new Long(integer.longValue());
Tom Tromey committed
785
      }
786
    catch (ArithmeticException e)
Tom Tromey committed
787
      {
788
        return new Double(bigDecimal.doubleValue());
Tom Tromey committed
789 790 791 792 793 794 795
      }
  }

  /**
   * Sets the <code>Currency</code> on the
   * <code>DecimalFormatSymbols</code> used, which also sets the
   * currency symbols on those symbols.
796 797 798
   * 
   * @param currency The new <code>Currency</code> on the
   * <code>DecimalFormatSymbols</code>.
Tom Tromey committed
799 800 801 802 803
   */
  public void setCurrency(Currency currency)
  {
    symbols.setCurrency(currency);
  }
804
  
Tom Tromey committed
805 806 807 808 809 810 811 812 813 814
  /**
   * Sets the symbols used by this instance.  This method makes a copy of 
   * the supplied symbols.
   * 
   * @param newSymbols  the symbols (<code>null</code> not permitted).
   */
  public void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols)
  {
    symbols = (DecimalFormatSymbols) newSymbols.clone();
  }
815 816 817 818 819 820 821 822 823 824 825
  
  /**
   * Define if the decimal separator should be always visible or only
   * visible when needed. This method as effect only on integer values.
   * Pass <code>true</code> if you want the decimal separator to be
   * always shown, <code>false</code> otherwise.
   * 
   * @param newValue true</code> if you want the decimal separator to be
   * always shown, <code>false</code> otherwise.
   */
  public void setDecimalSeparatorAlwaysShown(boolean newValue)
Tom Tromey committed
826 827 828
  {
    decimalSeparatorAlwaysShown = newValue;
  }
829 830 831 832 833 834 835 836 837 838
  
  /**
   * Sets the number of digits used to group portions of the integer part of
   * the number. For example, the number <code>123456</code>, with a grouping
   * size of 3, is rendered <code>123,456</code>.
   * 
   * @param groupSize The number of digits used while grouping portions
   * of the integer part of a number.
   */
  public void setGroupingSize(int groupSize)
Tom Tromey committed
839 840 841
  {
    groupingSize = (byte) groupSize;
  }
842 843 844 845 846 847 848 849 850 851 852
  
  /**
   * Sets the maximum number of digits allowed in the integer
   * portion of a number to the specified value.
   * The new value will be the choosen as the minimum between
   * <code>newvalue</code> and 309. Any value below zero will be
   * replaced by zero.
   * 
   * @param newValue The new maximum integer digits value.
   */
  public void setMaximumIntegerDigits(int newValue)
Tom Tromey committed
853
  {
854 855
    newValue = (newValue > 0) ? newValue : 0;
    super.setMaximumIntegerDigits(Math.min(newValue, DEFAULT_INTEGER_DIGITS));
Tom Tromey committed
856
  }
857 858 859 860 861 862 863 864 865 866 867
  
  /**
   * Sets the minimum number of digits allowed in the integer
   * portion of a number to the specified value.
   * The new value will be the choosen as the minimum between
   * <code>newvalue</code> and 309. Any value below zero will be
   * replaced by zero.
   * 
   * @param newValue The new minimum integer digits value.
   */
  public void setMinimumIntegerDigits(int newValue)
Tom Tromey committed
868
  {
869 870
    newValue = (newValue > 0) ? newValue : 0;
    super.setMinimumIntegerDigits(Math.min(newValue,  DEFAULT_INTEGER_DIGITS));
Tom Tromey committed
871
  }
872 873 874 875 876 877 878 879 880 881 882
  
  /**
   * Sets the maximum number of digits allowed in the fraction
   * portion of a number to the specified value.
   * The new value will be the choosen as the minimum between
   * <code>newvalue</code> and 309. Any value below zero will be
   * replaced by zero.
   * 
   * @param newValue The new maximum fraction digits value.
   */
  public void setMaximumFractionDigits(int newValue)
Tom Tromey committed
883
  {
884 885
    newValue = (newValue > 0) ? newValue : 0;
    super.setMaximumFractionDigits(Math.min(newValue, DEFAULT_FRACTION_DIGITS));
Tom Tromey committed
886
  }
887 888 889 890 891 892 893 894 895 896 897
  
  /**
   * Sets the minimum number of digits allowed in the fraction
   * portion of a number to the specified value.
   * The new value will be the choosen as the minimum between
   * <code>newvalue</code> and 309. Any value below zero will be
   * replaced by zero.
   * 
   * @param newValue The new minimum fraction digits value.
   */
  public void setMinimumFractionDigits(int newValue)
Tom Tromey committed
898
  {
899 900
    newValue = (newValue > 0) ? newValue : 0;
    super.setMinimumFractionDigits(Math.min(newValue, DEFAULT_FRACTION_DIGITS));
Tom Tromey committed
901
  }
902 903 904 905 906 907 908 909 910
  
  /**
   * Sets the multiplier for use in percent and similar formats.
   * For example, for percent set the multiplier to 100, for permille, set the
   * miltiplier to 1000.
   * 
   * @param newValue the new value for multiplier.
   */
  public void setMultiplier(int newValue)
Tom Tromey committed
911 912 913
  {
    multiplier = newValue;
  }
914 915 916 917 918 919 920
  
  /**
   * Sets the negative prefix.
   * 
   * @param newValue The new negative prefix.
   */
  public void setNegativePrefix(String newValue)
Tom Tromey committed
921 922 923 924
  {
    negativePrefix = newValue;
  }

925 926 927 928 929 930
  /**
   * Sets the negative suffix.
   * 
   * @param newValue The new negative suffix.
   */
  public void setNegativeSuffix(String newValue)
Tom Tromey committed
931 932 933
  {
    negativeSuffix = newValue;
  }
934 935 936 937 938 939 940
  
  /**
   * Sets the positive prefix.
   * 
   * @param newValue The new positive prefix.
   */
  public void setPositivePrefix(String newValue)
Tom Tromey committed
941 942 943
  {
    positivePrefix = newValue;
  }
944 945 946 947 948 949 950
  
  /**
   * Sets the new positive suffix.
   * 
   * @param newValue The new positive suffix.
   */
  public void setPositiveSuffix(String newValue)
Tom Tromey committed
951 952 953
  {
    positiveSuffix = newValue;
  }
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
  
  /**
   * This method returns a string with the formatting pattern being used
   * by this object. The string is localized.
   * 
   * @return A localized <code>String</code> with the formatting pattern.
   * @see #toPattern()
   */
  public String toLocalizedPattern()
  {
    return computePattern(this.symbols);
  }
  
  /**
   * This method returns a string with the formatting pattern being used
   * by this object. The string is not localized.
   * 
   * @return A <code>String</code> with the formatting pattern.
   * @see #toLocalizedPattern()
   */
  public String toPattern()
  {
    return computePattern(nonLocalizedSymbols);
  }
  
  /* ***** private methods ***** */
  
  /**
   * This is an shortcut helper method used to test if two given strings are
   * equals.
   * 
   * @param s1 The first string to test for equality.
   * @param s2 The second string to test for equality.
   * @return <code>true</code> if the strings are both <code>null</code> or
   * equals.
   */
  private boolean equals(String s1, String s2)
  {
    if (s1 == null || s2 == null)
      return s1 == s2;
    return s1.equals(s2);
  }
  
  
  /* ****** PATTERN ****** */
  
  /**
   * 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());
    buf.append(syms.getMinusSign());
    buf.append(syms.getPatternSeparator());
    buf.append(syms.getPercent());
    buf.append(syms.getPerMill());
    buf.append(syms.getZeroDigit());
    buf.append('\'');
    buf.append('\u00a4');
    
    return buf.toString();
  }
Tom Tromey committed
1022

1023 1024 1025 1026 1027 1028 1029 1030 1031
  /**
   * Quote special characters as defined by <code>patChars</code> in the
   * input string.
   * 
   * @param text
   * @param patChars
   * @return A StringBuffer with special characters quoted.
   */
  private StringBuffer quoteFix(String text, String patChars)
Tom Tromey committed
1032
  {
1033 1034
    StringBuffer buf = new StringBuffer();
    
Tom Tromey committed
1035
    int len = text.length();
1036
    char ch;
Tom Tromey committed
1037 1038
    for (int index = 0; index < len; ++index)
      {
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
        ch = text.charAt(index);
        if (patChars.indexOf(ch) != -1)
          {
            buf.append('\'');
            buf.append(ch);
            if (ch != '\'') buf.append('\'');
          }
        else
          {
            buf.append(ch);
          }
Tom Tromey committed
1050
      }
1051 1052
    
    return buf;
Tom Tromey committed
1053
  }
1054 1055 1056 1057 1058 1059
  
  /**
   * Returns the format pattern, localized to follow the given
   * symbols.
   */
  private String computePattern(DecimalFormatSymbols symbols)
Tom Tromey committed
1060
  {
1061 1062
    StringBuffer mainPattern = new StringBuffer();
    
Tom Tromey committed
1063
    // We have to at least emit a zero for the minimum number of
1064
    // digits. Past that we need hash marks up to the grouping
Tom Tromey committed
1065
    // separator (and one beyond).
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    int _groupingSize = groupingUsed ? groupingSize + 1: groupingSize;
    int totalDigits = Math.max(minimumIntegerDigits, _groupingSize);
    
    // if it is not in exponential notiation,
    // we always have a # prebended
    if (!useExponentialNotation) mainPattern.append(symbols.getDigit());
    
    for (int i = 1; i < totalDigits - minimumIntegerDigits; i++)
      mainPattern.append(symbols.getDigit());
    
    for (int i = totalDigits - minimumIntegerDigits; i < totalDigits; i++)
      mainPattern.append(symbols.getZeroDigit());
    
Tom Tromey committed
1079
    if (groupingUsed)
1080 1081 1082 1083 1084
      {
        mainPattern.insert(mainPattern.length() - groupingSize,
                           symbols.getGroupingSeparator());
      }

Tom Tromey committed
1085
    // See if we need decimal info.
1086 1087 1088 1089 1090 1091
    if (minimumFractionDigits > 0 || maximumFractionDigits > 0 ||
        decimalSeparatorAlwaysShown)
      {
        mainPattern.append(symbols.getDecimalSeparator());
      }
    
Tom Tromey committed
1092
    for (int i = 0; i < minimumFractionDigits; ++i)
1093 1094
      mainPattern.append(symbols.getZeroDigit());
    
Tom Tromey committed
1095
    for (int i = minimumFractionDigits; i < maximumFractionDigits; ++i)
1096 1097
      mainPattern.append(symbols.getDigit());
    
Tom Tromey committed
1098 1099
    if (useExponentialNotation)
      {
1100 1101 1102 1103 1104 1105 1106
        mainPattern.append(symbols.getExponential());
        
        for (int i = 0; i < minExponentDigits; ++i)
          mainPattern.append(symbols.getZeroDigit());
        
        if (minExponentDigits == 0)
          mainPattern.append(symbols.getDigit());
Tom Tromey committed
1107
      }
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    
    // save the pattern
    String pattern = mainPattern.toString();
    
    // so far we have the pattern itself, now we need to add
    // the positive and the optional negative prefixes and suffixes
    String patternChars = patternChars(symbols);
    mainPattern.insert(0, quoteFix(positivePrefix, patternChars));
    mainPattern.append(quoteFix(positiveSuffix, patternChars));
    
    if (hasNegativePrefix)
Tom Tromey committed
1119
      {
1120 1121 1122 1123
        mainPattern.append(symbols.getPatternSeparator());
        mainPattern.append(quoteFix(negativePrefix, patternChars));
        mainPattern.append(pattern);
        mainPattern.append(quoteFix(negativeSuffix, patternChars));
Tom Tromey committed
1124
      }
1125 1126
    
    // finally, return the pattern string
Tom Tromey committed
1127 1128
    return mainPattern.toString();
  }
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
  
  /* ****** FORMAT PARSING ****** */
  
  /**
   * Scan the input string and define a pattern suitable for use
   * with this decimal format.
   * 
   * @param pattern
   * @param symbols
   */
  private void applyPatternWithSymbols(String pattern,
                                       DecimalFormatSymbols symbols)
Tom Tromey committed
1141
  {
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
    // The pattern string is described by a BNF diagram.
    // we could use a recursive parser to read and prepare
    // the string, but this would be too slow and resource
    // intensive, while this code is quite critical as it is
    // called always when the class is instantiated and every
    // time a new pattern is given.
    // Our strategy is to divide the string into section as given by
    // the BNF diagram, iterating through the string and setting up
    // the parameters we need for formatting (which is basicly what
    // a descendent recursive parser would do - but without recursion).
    // I'm sure that there are smarter methods to do this.
    
    // Restore default values. Most of these will be overwritten
    // but we want to be sure that nothing is left out.
    setDefaultValues();
    
    int len = pattern.length();
    if (len == 0)
      {
        // this is another special case...
        this.minimumIntegerDigits = 1;
        this.maximumIntegerDigits = DEFAULT_INTEGER_DIGITS;
        this.minimumFractionDigits = 0;
        this.maximumFractionDigits = DEFAULT_FRACTION_DIGITS;
        
        // FIXME: ...and these values may not be valid in all locales
        this.minExponentDigits = 0;
        this.showDecimalSeparator = true;
        this.groupingUsed = true;
        this.groupingSize = 3;
        
        return;
      }
    
    int start = scanFix(pattern, symbols, 0, true);
    if (start < len) start = scanNumberInteger(pattern, symbols, start);
    if (start < len)
      {
        start = scanFractionalPortion(pattern, symbols, start);
      }
    else
      {
        // special case, pattern that ends here does not have a fractional
        // portion
        this.minimumFractionDigits = 0;
        this.maximumFractionDigits = 0;
        //this.decimalSeparatorAlwaysShown = false;
        //this.showDecimalSeparator = false;
      }
    
    // XXX: this fixes a compatibility test with the RI.
    // If new uses cases fail, try removing this line first.
    //if (!this.hasIntegerPattern && !this.hasFractionalPattern)
    //  throw new IllegalArgumentException("No valid pattern found!");
    
    if (start < len) start = scanExponent(pattern, symbols, start);
    if (start < len) start = scanFix(pattern, symbols, start, false);
    if (start < len) scanNegativePattern(pattern, symbols, start);
    
    if (useExponentialNotation &&
        (maxIntegerDigitsExponent > minimumIntegerDigits) &&
        (maxIntegerDigitsExponent > 1))
      {
        minimumIntegerDigits = 1;
        exponentRound = maxIntegerDigitsExponent;
      }
    
    if (useExponentialNotation)
      maximumIntegerDigits = maxIntegerDigitsExponent;
    
    if (!this.hasFractionalPattern && this.showDecimalSeparator == true)
      {
        this.decimalSeparatorAlwaysShown = true;
      }
  }
  
  /**
   * Scans for the prefix or suffix portion of the pattern string.
   * This method handles the positive subpattern of the pattern string.
   *  
   * @param pattern The pattern string to parse.
   * @return The position in the pattern string where parsing ended.
   */
  private int scanFix(String pattern, DecimalFormatSymbols sourceSymbols,
                      int start, boolean prefix)
  {
    StringBuffer buffer = new StringBuffer();
    
    // the number portion is always delimited by one of those
    // characters
    char decimalSeparator = sourceSymbols.getDecimalSeparator();
    char patternSeparator = sourceSymbols.getPatternSeparator();
    char groupingSeparator = sourceSymbols.getGroupingSeparator();
    char digit = sourceSymbols.getDigit();
    char zero = sourceSymbols.getZeroDigit();
    char minus = sourceSymbols.getMinusSign();
    
    // other special characters, cached here to avoid method calls later
    char percent = sourceSymbols.getPercent();
    char permille = sourceSymbols.getPerMill();
    
    String currencySymbol = this.symbols.getCurrencySymbol();
    
    boolean quote = false;
    
    char ch = pattern.charAt(start);
    if (ch == patternSeparator)
      {
        // negative subpattern
        this.hasNegativePrefix = true;
        ++start;
        return start;
      }
    
    int len = pattern.length();
    int i;
    for (i = start; i < len; i++)
      {
        ch = pattern.charAt(i);

        // we are entering into the negative subpattern
        if (!quote && ch == patternSeparator)
          {
            if (this.hasNegativePrefix)
              {
                throw new IllegalArgumentException("Invalid pattern found: "
                                                   + start);
              }
            
            this.hasNegativePrefix = true;
            ++i;
            break;
          }
        
        // this means we are inside the number portion
        if (!quote &&
            (ch == minus || ch == digit || ch == zero ||
             ch == groupingSeparator))
          break;

        if (!quote && ch == decimalSeparator)
          {
            this.showDecimalSeparator = true;
            break;
          }
        else if (quote && ch != '\'')
          {
            buffer.append(ch);
            continue;
          }
        
        if (ch == '\u00A4')
          {
            // CURRENCY
            currencySymbol = this.symbols.getCurrencySymbol();

            // if \u00A4 is doubled, we use the international currency symbol
            if (i < len && pattern.charAt(i + 1) == '\u00A4')
              {
                currencySymbol = this.symbols.getInternationalCurrencySymbol();
                i++;
              }

            this.useCurrencySeparator = true;
            buffer.append(currencySymbol);
          }
        else if (ch == percent)
          {
            // PERCENT
            this.multiplier = 100;
            buffer.append(this.symbols.getPercent());
          }
        else if (ch == permille)
          {
            // PERMILLE
            this.multiplier = 1000;
            buffer.append(this.symbols.getPerMill());
          }
        else if (ch == '\'')
          {
            // QUOTE
            if (i < len && pattern.charAt(i + 1) == '\'')
              {
                // we need to add ' to the buffer 
                buffer.append(ch);
                i++;
              }
            else
              {
                quote = !quote;
                continue;
              }
          }
        else
          {
            buffer.append(ch);
          }
      }
    
    if (prefix)
      {
        this.positivePrefix = buffer.toString();
        this.negativePrefix = minus + "" + positivePrefix;
      }
    else
      {
        this.positiveSuffix = buffer.toString();
      }
    
    return i;
  }
  
  /**
   * Scan the given string for number patterns, starting
   * from <code>start</code>.
   * This method searches the integer part of the pattern only.
   * 
   * @param pattern The pattern string to parse.
   * @param start The starting parse position in the string.
   * @return The position in the pattern string where parsing ended,
   * counted from the beginning of the string (that is, 0).
   */
  private int scanNumberInteger(String pattern, DecimalFormatSymbols symbols,
                                int start)
  {
    char digit = symbols.getDigit();
    char zero = symbols.getZeroDigit();
    char groupingSeparator = symbols.getGroupingSeparator();
    char decimalSeparator = symbols.getDecimalSeparator();
    char exponent = symbols.getExponential();
    char patternSeparator = symbols.getPatternSeparator();
    
    // count the number of zeroes in the pattern
    // this number defines the minum digits in the integer portion
    int zeros = 0;
    
    // count the number of digits used in grouping
    int _groupingSize = 0;
    
    this.maxIntegerDigitsExponent = 0;
    
    boolean intPartTouched = false;
    
    char ch;
    int len = pattern.length();
    int i;
    for (i = start; i < len; i++)
      {
        ch = pattern.charAt(i);
 
        // break on decimal separator or exponent or pattern separator
        if (ch == decimalSeparator || ch == exponent)
          break;
        
        if (this.hasNegativePrefix && ch == patternSeparator)
          throw new IllegalArgumentException("Invalid pattern found: "
                                             + start);
        
        if (ch == digit)
          {
            // in our implementation we could relax this strict
            // requirement, but this is used to keep compatibility with
            // the RI
            if (zeros > 0) throw new
              IllegalArgumentException("digit mark following zero in " +
                        "positive subpattern, not allowed. Position: " + i);
            
            _groupingSize++;
            intPartTouched = true;
            this.maxIntegerDigitsExponent++;
          }
        else if (ch == zero)
          {
            zeros++;
            _groupingSize++;
            this.maxIntegerDigitsExponent++;
          }
        else if (ch == groupingSeparator)
          {
            this.groupingSeparatorInPattern = true;
            this.groupingUsed = true;
            _groupingSize = 0;
          }
        else
          {
            // any other character not listed above
            // means we are in the suffix portion
            break;
          }
      }
    
    if (groupingSeparatorInPattern) this.groupingSize = (byte) _groupingSize;
    this.minimumIntegerDigits = zeros;
    
    // XXX: compatibility code with the RI: the number of minimum integer
    // digits is at least one when maximumIntegerDigits is more than zero
    if (intPartTouched && this.maximumIntegerDigits > 0 &&
        this.minimumIntegerDigits == 0)
      this.minimumIntegerDigits = 1;
Tom Tromey committed
1441

1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
    return i;
  }
  
  /**
   * Scan the given string for number patterns, starting
   * from <code>start</code>.
   * This method searches the fractional part of the pattern only.
   * 
   * @param pattern The pattern string to parse.
   * @param start The starting parse position in the string.
   * @return The position in the pattern string where parsing ended,
   * counted from the beginning of the string (that is, 0).
   */
  private int scanFractionalPortion(String pattern,
                                    DecimalFormatSymbols symbols,
                                    int start)
  {
    char digit = symbols.getDigit();
    char zero = symbols.getZeroDigit();
    char groupingSeparator = symbols.getGroupingSeparator();
    char decimalSeparator = symbols.getDecimalSeparator();
    char exponent = symbols.getExponential();
    char patternSeparator = symbols.getPatternSeparator();
    
    // first character needs to be '.' otherwise we are not parsing the
    // fractional portion
    char ch = pattern.charAt(start);
    if (ch != decimalSeparator)
      {
        this.minimumFractionDigits = 0;
        this.maximumFractionDigits = 0;
        return start;
      }
    
    ++start;
    
    this.hasFractionalPattern = true;
    
    this.minimumFractionDigits = 0;
    int digits = 0;
    
    int len = pattern.length();
    int i;
    for (i = start; i < len; i++)
      {
        ch = pattern.charAt(i);
        
        // we hit the exponential or negative subpattern
        if (ch == exponent || ch == patternSeparator)
          break;
        
        // pattern error
        if (ch == groupingSeparator || ch == decimalSeparator) throw new
          IllegalArgumentException("unexpected character '" + ch + "' " +
                                   "in fractional subpattern. Position: " + i);
        
        if (ch == digit)
          {
            digits++;
          }
        else if (ch == zero)
          {
            if (digits > 0) throw new
            IllegalArgumentException("digit mark following zero in " +
                      "positive subpattern, not allowed. Position: " + i);
            
            this.minimumFractionDigits++;
          }
        else
          {
            // we are in the suffix section of pattern
            break;
          }
      }
    
    if (i == start) this.hasFractionalPattern = false;
    
    this.maximumFractionDigits = this.minimumFractionDigits + digits;
    this.showDecimalSeparator = true;
    
    return i;
  }
  
  /**
   * Scan the given string for number patterns, starting
   * from <code>start</code>.
   * This method searches the expoential part of the pattern only.
   * 
   * @param pattern The pattern string to parse.
   * @param start The starting parse position in the string.
   * @return The position in the pattern string where parsing ended,
   * counted from the beginning of the string (that is, 0).
   */
  private int scanExponent(String pattern, DecimalFormatSymbols symbols,
                           int start)
Tom Tromey committed
1537
  {
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
    char digit = symbols.getDigit();
    char zero = symbols.getZeroDigit();
    char groupingSeparator = symbols.getGroupingSeparator();
    char decimalSeparator = symbols.getDecimalSeparator();
    char exponent = symbols.getExponential();
    
    char ch = pattern.charAt(start);
    
    if (ch == decimalSeparator)
      {
        // ignore dots
        ++start;
      }
    
    if (ch != exponent)
      {
        this.useExponentialNotation = false;
        return start;
      }
    
    ++start;
    
    this.minExponentDigits = 0;
    
    int len = pattern.length();
    int i;
    for (i = start; i < len; i++)
      {
        ch = pattern.charAt(i);
        
        if (ch == groupingSeparator || ch == decimalSeparator ||
            ch == digit || ch == exponent) throw new
        IllegalArgumentException("unexpected character '" + ch + "' " + 
                                 "in exponential subpattern. Position: " + i);
        
        if (ch == zero)
          {
            this.minExponentDigits++;
          }
        else
          {
            // any character other than zero is an exit point
            break;
          }
      }
    
    this.useExponentialNotation = true; 
    
    return i;
  }
  
  /**
   * Scan the given string for number patterns, starting
   * from <code>start</code>.
   * This method searches the negative part of the pattern only and scan
   * throught the end of the string.
   * 
   * @param pattern The pattern string to parse.
   * @param start The starting parse position in the string.
   */
  private void scanNegativePattern(String pattern,
                                   DecimalFormatSymbols sourceSymbols,
                                   int start)
  {
    StringBuffer buffer = new StringBuffer();
    
    // the number portion is always delimited by one of those
    // characters
    char decimalSeparator = sourceSymbols.getDecimalSeparator();
    char patternSeparator = sourceSymbols.getPatternSeparator();
    char groupingSeparator = sourceSymbols.getGroupingSeparator();
    char digit = sourceSymbols.getDigit();
    char zero = sourceSymbols.getZeroDigit();
    char minus = sourceSymbols.getMinusSign();
    
    // other special charcaters, cached here to avoid method calls later
    char percent = sourceSymbols.getPercent();
    char permille = sourceSymbols.getPerMill();
    
    String CURRENCY_SYMBOL = this.symbols.getCurrencySymbol();
    String currencySymbol = CURRENCY_SYMBOL;
    
    boolean quote = false;
    boolean prefixDone = false;
    
    int len = pattern.length();
    if (len > 0) this.hasNegativePrefix = true;
    
    char ch = pattern.charAt(start);
    if (ch == patternSeparator)
      {
        // no pattern separator in the negative pattern
        if ((start + 1) > len) throw new
          IllegalArgumentException("unexpected character '" + ch + "' " +
                                   "in negative subpattern.");    
        start++;
      }
    
    int i;
    for (i = start; i < len; i++)
      {
        ch = pattern.charAt(i);
        
        // this means we are inside the number portion
        if (!quote &&
            (ch == digit || ch == zero || ch == decimalSeparator ||
             ch == patternSeparator || ch == groupingSeparator))
          {
            if (!prefixDone)
              {
                this.negativePrefix = buffer.toString();
                buffer.delete(0, buffer.length());
                prefixDone = true;
              }
          }
        else if (ch == minus)
          {
            buffer.append(this.symbols.getMinusSign());
          }
        else if (quote && ch != '\'')
          {
            buffer.append(ch);
          }
        else if (ch == '\u00A4')
          {
            // CURRENCY
            currencySymbol = CURRENCY_SYMBOL;

            // if \u00A4 is doubled, we use the international currency symbol
            if ((i + 1) < len && pattern.charAt(i + 1) == '\u00A4')
              {
                currencySymbol = this.symbols.getInternationalCurrencySymbol();
                i = i + 2;
              }

            // FIXME: not sure about this, the specs says that we only have to
            // change prefix and suffix, so leave it as commented
            // unless in case of bug report/errors
            //this.useCurrencySeparator = true;
            
            buffer.append(currencySymbol);
          }
        else if (ch == percent)
          {
            // PERCENT
            this.negativePatternMultiplier = 100;
            buffer.append(this.symbols.getPercent());
          }
        else if (ch == permille)
          {
            // PERMILLE
            this.negativePatternMultiplier = 1000;
            buffer.append(this.symbols.getPerMill());
          }
        else if (ch == '\'')
          {
            // QUOTE
            if (i < len && pattern.charAt(i + 1) == '\'')
              {
                // we need to add ' to the buffer 
                buffer.append(ch);
                i++;
              }
            else
              {
                quote = !quote;
              }
          }
        else if (ch == patternSeparator)
          {
            // no pattern separator in the negative pattern
            throw new IllegalArgumentException("unexpected character '" + ch +
                                               "' in negative subpattern.");
          }
        else
          {
            buffer.append(ch);
          }
      }
    
    if (prefixDone)
      this.negativeSuffix = buffer.toString();
    else
      this.negativePrefix = buffer.toString();
  }
  
  /* ****** FORMATTING ****** */
  
  /**
   * Handles the real formatting.
   * 
   * We use a BigDecimal to format the number without precision loss.
   * All the rounding is done by methods in BigDecimal.
   * The <code>isLong</code> parameter is used to determine if we are
   * formatting a long or BigInteger. In this case, we avoid to format
   * the fractional part of the number (unless specified otherwise in the
   * format string) that would consist only of a 0 digit.
   * 
   * @param number A BigDecimal representation fo the input number.
   * @param dest The destination buffer.
   * @param isLong A boolean that indicates if this BigDecimal is a real
   * decimal or an integer.
   * @param fieldPos Use to keep track of the formatting position.
   */
  private void formatInternal(BigDecimal number, boolean isLong,
                              StringBuffer dest, FieldPosition fieldPos)
  {  
    // The specs says that fieldPos should not be null, and that we
    // should throw a NPE, but it seems that in few classes that
    // reference this one, fieldPos is set to null.
    // This is even defined in the javadoc, see for example MessageFormat.
    // I think the best here is to check for fieldPos and build one if it is
    // null. If it cause harms or regressions, just remove this line and
    // fix the classes in the point of call, insted.
    if (fieldPos == null) fieldPos = new FieldPosition(0);
    
    int _multiplier = this.multiplier;
    
    // used to track attribute starting position for each attribute
    int attributeStart = -1;
    
    // now get the sign this will be used by the special case Inifinity
    // and by the normal cases.
    boolean isNegative = (number.signum() < 0) ? true : false;
    if (isNegative)
      {
        attributeStart = dest.length();
        
        // append the negative prefix to the string
        dest.append(negativePrefix);
        
        // once got the negative prefix, we can use
        // the absolute value.
        number = number.abs();
        
        _multiplier = negativePatternMultiplier;
        
        addAttribute(Field.SIGN, attributeStart, dest.length());
      }
    else
      {
        // not negative, use the positive prefix
        dest.append(positivePrefix);
      }
    
    // these are used ot update the field position
    int beginIndexInt = dest.length();
    int endIndexInt = 0;
    int beginIndexFract = 0;
    int endIndexFract = 0;
    
    // compute the multiplier to use with percent and similar
    number = number.multiply(new BigDecimal(_multiplier));
    
    // XXX: special case, not sure if it belongs here or if it is
    // correct at all. There may be other special cases as well
    // these should be handled in the format string parser.
    if (this.maximumIntegerDigits == 0 && this.maximumFractionDigits == 0)
      {
        number = BigDecimal.ZERO;
        this.maximumIntegerDigits = 1;
        this.minimumIntegerDigits = 1;
      }
    
    //  get the absolute number
    number = number.abs();

    // the scaling to use while formatting this number
    int scale = this.maximumFractionDigits;
    
    // this is the actual number we will use
    // it is corrected later on to handle exponential
    // notation, if needed
    long exponent = 0;
    
    // are we using exponential notation?
    if (this.useExponentialNotation)
      {
        exponent = getExponent(number);
        number = number.movePointLeft((int) exponent);
        
        // FIXME: this makes the test ##.###E0 to pass,
        // but all all the other tests to fail...
        // this should be really something like
        // min + max - what is already shown...
        //scale = this.minimumIntegerDigits + this.maximumFractionDigits;
      }
    
    // round the number to the nearest neighbor
    number = number.setScale(scale, BigDecimal.ROUND_HALF_EVEN);

    // now get the integer and fractional part of the string
    // that will be processed later
    String plain = number.toPlainString();
    
    String intPart = null;
    String fractPart = null;
    
    // remove - from the integer part, this is needed as
    // the Narrowing Primitive Conversions algorithm used may loose
    // information about the sign
    int minusIndex = plain.lastIndexOf('-', 0);
    if (minusIndex > -1) plain = plain.substring(minusIndex + 1);
    
    // strip the decimal portion
    int dot = plain.indexOf('.');
    if (dot > -1)
      {
        intPart = plain.substring(0, dot);
        dot++;
        
        if (useExponentialNotation)
          fractPart = plain.substring(dot, dot + scale);
        else
          fractPart = plain.substring(dot);
      }
    else
      {
        intPart = plain;
      }
    
    // used in various places later on
    int intPartLen = intPart.length();
    endIndexInt = intPartLen;
    
    // if the number of digits in our intPart is not greater than the
    // minimum we have to display, we append zero to the destination
    // buffer before adding the integer portion of the number.
    int zeroes = minimumIntegerDigits - intPartLen;
    if (zeroes > 0)
      {
        attributeStart = Math.max(dest.length() - 1, 0);
        appendZero(dest, zeroes, minimumIntegerDigits);
      }

    if (this.useExponentialNotation)
      {
        // For exponential numbers, the significant in mantissa are
        // the sum of the minimum integer and maximum fraction
        // digits, and does not take into account the maximun integer
        // digits to display.
        
        if (attributeStart < 0)
          attributeStart = Math.max(dest.length() - 1, 0);
        appendDigit(intPart, dest, this.groupingUsed);
      }
    else
      {
        // non exponential notation
        intPartLen = intPart.length();
        int canary = Math.min(intPartLen, this.maximumIntegerDigits);
        
        // remove from the string the number in excess
        // use only latest digits
        intPart = intPart.substring(intPartLen - canary);
        endIndexInt = intPart.length() + 1;
        
        // append it
        if (maximumIntegerDigits > 0 &&
            !(this.minimumIntegerDigits == 0 &&
             intPart.compareTo(String.valueOf(symbols.getZeroDigit())) == 0))
          {
            if (attributeStart < 0)
              attributeStart = Math.max(dest.length() - 1, 0);
            appendDigit(intPart, dest, this.groupingUsed);
          }
      }
    
    // add the INTEGER attribute
    addAttribute(Field.INTEGER, attributeStart, dest.length());
    
    // ...update field position, if needed, and return...
    if ((fieldPos.getField() == INTEGER_FIELD ||
        fieldPos.getFieldAttribute() == NumberFormat.Field.INTEGER))
      {
        fieldPos.setBeginIndex(beginIndexInt);
        fieldPos.setEndIndex(endIndexInt);
      }
    
    handleFractionalPart(dest, fractPart, fieldPos, isLong);
        
    // and the exponent
    if (this.useExponentialNotation)
      {
        attributeStart = dest.length();
        
        dest.append(symbols.getExponential());
        
        addAttribute(Field.EXPONENT_SYMBOL, attributeStart, dest.length());
        attributeStart = dest.length();
        
        if (exponent < 0)
          {
            dest.append(symbols.getMinusSign());
            exponent = -exponent;
            
            addAttribute(Field.EXPONENT_SIGN, attributeStart, dest.length());
          }
        
        attributeStart = dest.length();
        
        String exponentString = String.valueOf(exponent);
        int exponentLength = exponentString.length();
        
        for (int i = 0; i < minExponentDigits - exponentLength; i++)
          dest.append(symbols.getZeroDigit());
        
        for (int i = 0; i < exponentLength; ++i)
          dest.append(exponentString.charAt(i));
        
        addAttribute(Field.EXPONENT, attributeStart, dest.length());
      }
 
    // now include the suffixes...
    if (isNegative)
      {
        dest.append(negativeSuffix);
      }
    else
Tom Tromey committed
1957
      {
1958
        dest.append(positiveSuffix);
Tom Tromey committed
1959 1960 1961
      }
  }

1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
  /**
   * Add to the input buffer the result of formatting the fractional
   * portion of the number.
   * 
   * @param dest
   * @param fractPart
   * @param fieldPos
   * @param isLong
   */
  private void handleFractionalPart(StringBuffer dest, String fractPart,
                                    FieldPosition fieldPos, boolean isLong)
  {
    int dotStart = 0;
    int dotEnd = 0;
    boolean addDecimal = false;
    
    if (this.decimalSeparatorAlwaysShown  ||
         ((!isLong || this.useExponentialNotation) &&
           this.showDecimalSeparator && this.maximumFractionDigits > 0) ||
        this.minimumFractionDigits > 0)
      {
        dotStart = dest.length();
        
        if (this.useCurrencySeparator)
          dest.append(symbols.getMonetaryDecimalSeparator());
        else
          dest.append(symbols.getDecimalSeparator());
        
        dotEnd = dest.length();
        addDecimal = true;
      }
    
    // now handle the fraction portion of the number
    int fractStart = 0;
    int fractEnd = 0;
    boolean addFractional = false;
    
    if ((!isLong || this.useExponentialNotation)
        && this.maximumFractionDigits > 0
        || this.minimumFractionDigits > 0)
      {
        fractStart = dest.length();
        fractEnd = fractStart;
        
        int digits = this.minimumFractionDigits;
        
        if (this.useExponentialNotation)
          {
            digits = (this.minimumIntegerDigits + this.minimumFractionDigits)
              - dest.length();
            if (digits < 0) digits = 0;
          }
        
        fractPart = adjustTrailingZeros(fractPart, digits);
        
        // FIXME: this code must be improved
        // now check if the factional part is just 0, in this case
        // we need to remove the '.' unless requested
        boolean allZeros = true;
        char fracts[] = fractPart.toCharArray();
        for (int i = 0; i < fracts.length; i++)
          {
            if (fracts[i] != '0')
              allZeros = false;
          }
        
        if (!allZeros || (minimumFractionDigits > 0))
          {
            appendDigit(fractPart, dest, false);
            fractEnd = dest.length();
            
            addDecimal = true;
            addFractional = true;
          }
        else if (!this.decimalSeparatorAlwaysShown)
          {
            dest.deleteCharAt(dest.length() - 1);
            addDecimal = false;
          }
        else
          {
            fractEnd = dest.length();
            addFractional = true;
          }
      }
    
    if (addDecimal)
      addAttribute(Field.DECIMAL_SEPARATOR, dotStart, dotEnd);
    
    if (addFractional)
      addAttribute(Field.FRACTION, fractStart, fractEnd);
    
    if ((fieldPos.getField() == FRACTION_FIELD ||
        fieldPos.getFieldAttribute() == NumberFormat.Field.FRACTION))
      {
        fieldPos.setBeginIndex(fractStart);
        fieldPos.setEndIndex(fractEnd);
      }
  }
  
  /**
   * Append to <code>dest</code>the give number of zeros.
   * Grouping is added if needed.
   * The integer totalDigitCount defines the total number of digits
   * of the number to which we are appending zeroes.
   */
  private void appendZero(StringBuffer dest, int zeroes, int totalDigitCount)
  {
    char ch = symbols.getZeroDigit();
    char gSeparator = symbols.getGroupingSeparator();
    
    int i = 0;
    int gPos = totalDigitCount;
    for (i = 0; i < zeroes; i++, gPos--)
      {
        if (this.groupingSeparatorInPattern &&
            (this.groupingUsed && this.groupingSize != 0) &&
            (gPos % groupingSize == 0 && i > 0))
          dest.append(gSeparator);
        
        dest.append(ch);
      }
    
    // special case, that requires adding an additional separator
    if (this.groupingSeparatorInPattern &&
        (this.groupingUsed && this.groupingSize != 0) &&
        (gPos % groupingSize == 0))
      dest.append(gSeparator);
  }
  
  /**
   * Append src to <code>dest</code>.
   * 
   * Grouping is added if <code>groupingUsed</code> is set
   * to <code>true</code>.
   */
  private void appendDigit(String src, StringBuffer dest,
                             boolean groupingUsed)
  {
    int zero = symbols.getZeroDigit() - '0';
    
    int ch;
    char gSeparator = symbols.getGroupingSeparator();
        
    int len = src.length();
    for (int i = 0, gPos = len; i < len; i++, gPos--)
      {
        ch = src.charAt(i);
        if (groupingUsed && this.groupingSize != 0 &&
            gPos % groupingSize == 0 && i > 0)
          dest.append(gSeparator);
Tom Tromey committed
2113

2114 2115 2116 2117
        dest.append((char) (zero + ch));
      }
  }
  
Tom Tromey committed
2118
  /**
2119 2120 2121 2122
   * Calculate the exponent to use if eponential notation is used.
   * The exponent is calculated as a power of ten.
   * <code>number</code> should be positive, if is zero, or less than zero,
   * zero is returned.
Tom Tromey committed
2123
   */
2124
  private long getExponent(BigDecimal number)
Tom Tromey committed
2125
  {
2126
    long exponent = 0;
Tom Tromey committed
2127
    
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
    if (number.signum() > 0)
      {
        double _number = number.doubleValue();
        exponent = (long) Math.floor (Math.log10(_number));
        
        // get the right value for the exponent
        exponent = exponent - (exponent % this.exponentRound);
        
        // if the minimumIntegerDigits is more than zero
        // we display minimumIntegerDigits of digits.
        // so, for example, if minimumIntegerDigits == 2
        // and the actual number is 0.123 it will be
        // formatted as 12.3E-2
        // this means that the exponent have to be shifted
        // to the correct value.
        if (minimumIntegerDigits > 0)
              exponent -= minimumIntegerDigits - 1;
      }
    
    return exponent;
  }
 
  /**
   * Remove contiguos zeros from the end of the <code>src</code> string,
   * if src contains more than <code>minimumDigits</code> digits.
   * if src contains less that <code>minimumDigits</code>,
   * then append zeros to the string.
   * 
   * Only the first block of zero digits is removed from the string
   * and only if they fall in the src.length - minimumDigits
   * portion of the string.
   * 
   * @param src The string with the correct number of zeros.
   */
  private String adjustTrailingZeros(String src, int minimumDigits)
  {
    int len = src.length();
    String result;
Tom Tromey committed
2166
    
2167 2168
    // remove all trailing zero
    if (len > minimumDigits)
Tom Tromey committed
2169
      {
2170 2171 2172 2173 2174 2175 2176 2177 2178
        int zeros = 0;    
        for (int i = len - 1; i > minimumDigits; i--)
          {
            if (src.charAt(i) == '0')
              ++zeros;
            else
              break;
          }
        result =  src.substring(0, len - zeros);                
Tom Tromey committed
2179
      }
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
    else
      {
        char zero = symbols.getZeroDigit();
        StringBuffer _result = new StringBuffer(src);
        for (int i = len; i < minimumDigits; i++)
          {
            _result.append(zero);
          }
        result = _result.toString();
      }
    
    return result;
Tom Tromey committed
2192 2193
  }
  
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
  /**
   * Adds an attribute to the attributes list.
   * 
   * @param field
   * @param begin
   * @param end
   */
  private void addAttribute(Field field, int begin, int end)
  {
    /*
     * This method and its implementation derives directly from the
     * ICU4J (http://icu.sourceforge.net/) library, distributed under MIT/X.
     */
    
    FieldPosition pos = new FieldPosition(field);
    pos.setBeginIndex(begin);
    pos.setEndIndex(end);
    attributes.add(pos);
  }
  
  /**
   * Sets the default values for the various properties in this DecimaFormat.
   */
  private void setDefaultValues()
  {
    // Maybe we should add these values to the message bundle and take
    // the most appropriate for them for any locale.
    // Anyway, these seem to be good values for a default in most languages.
    // Note that most of these will change based on the format string.
    
    this.negativePrefix = String.valueOf(symbols.getMinusSign());
    this.negativeSuffix = "";
    this.positivePrefix = "";
    this.positiveSuffix = "";
    
    this.multiplier = 1;
    this.negativePatternMultiplier = 1;
    this.exponentRound = 1;
    
    this.hasNegativePrefix = false;
    
    this.minimumIntegerDigits = 1;
    this.maximumIntegerDigits = DEFAULT_INTEGER_DIGITS;
    this.minimumFractionDigits = 0;
    this.maximumFractionDigits = DEFAULT_FRACTION_DIGITS;
    this.minExponentDigits = 0;
    
    this.groupingSize = 0;
    
    this.decimalSeparatorAlwaysShown = false;
    this.showDecimalSeparator = false;
    this.useExponentialNotation = false;
    this.groupingUsed = false;
    this.groupingSeparatorInPattern = false;
    
    this.useCurrencySeparator = false;
    
    this.hasFractionalPattern = false;
  }
Tom Tromey committed
2253
}