DecimalFormat.java 68.7 KB
Newer Older
Tom Tromey committed
1 2 3 4 5 6 7 8 9
/* 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.
10

Tom Tromey committed
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
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 gnu.java.lang.CPStringBuilder;

48 49
import java.math.BigDecimal;
import java.math.BigInteger;
Tom Tromey committed
50

51
import java.util.ArrayList;
Tom Tromey committed
52 53 54
import java.util.Currency;
import java.util.Locale;

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

/**
 * 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.
75
 *
76
 * @author Mario Torre (neugens@limasoftware.net)
77 78 79
 * @author Tom Tromey (tromey@cygnus.com)
 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
 */
Tom Tromey committed
80 81
public class DecimalFormat extends NumberFormat
{
82 83
  /** serialVersionUID for serializartion. */
  private static final long serialVersionUID = 864413376551465018L;
84

85
  /** Defines the default number of digits allowed while formatting integers. */
86
  private static final int DEFAULT_INTEGER_DIGITS = 309;
Tom Tromey committed
87 88

  /**
89 90 91 92
   * Defines the default number of digits allowed while formatting
   * fractions.
   */
  private static final int DEFAULT_FRACTION_DIGITS = 340;
93

94 95 96 97 98 99
  /**
   * Locale-independent pattern symbols.
   */
  // Happen to be the same as the US symbols.
  private static final DecimalFormatSymbols nonLocalizedSymbols
    = new DecimalFormatSymbols (Locale.US);
100

101 102 103 104
  /**
   * Defines if parse should return a BigDecimal or not.
   */
  private boolean parseBigDecimal;
105

106 107 108 109 110
  /**
   * Defines if we have to use the monetary decimal separator or
   * the decimal separator while formatting numbers.
   */
  private boolean useCurrencySeparator;
111

112 113
  /** Defines if the decimal separator is always shown or not. */
  private boolean decimalSeparatorAlwaysShown;
114

115 116
  /**
   * Defines if the decimal separator has to be shown.
117
   *
118 119 120 121
   * This is different then <code>decimalSeparatorAlwaysShown</code>,
   * as it defines if the format string contains a decimal separator or no.
   */
  private boolean showDecimalSeparator;
122

123 124 125 126 127 128
  /**
   * 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;
129

130 131
  /** Defines the size of grouping groups when grouping is used. */
  private byte groupingSize;
132

133 134 135 136 137 138
  /**
   * 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;
139

140 141
  /** This field is used to set the exponent in the engineering notation. */
  private int exponentRound;
142

143 144
  /** Multiplier used in percent style formats. */
  private int multiplier;
145

146 147
  /** Multiplier used in percent style formats. */
  private int negativePatternMultiplier;
148

149 150
  /** The negative prefix. */
  private String negativePrefix;
151

152 153
  /** The negative suffix. */
  private String negativeSuffix;
154

155 156
  /** The positive prefix. */
  private String positivePrefix;
157

158 159
  /** The positive suffix. */
  private String positiveSuffix;
160

161 162
  /** Decimal Format Symbols for the given locale. */
  private DecimalFormatSymbols symbols;
163

164 165
  /** Determine if we have to use exponential notation or not. */
  private boolean useExponentialNotation;
166

167 168 169 170 171
  /**
   * Defines the maximum number of integer digits to show when we use
   * the exponential notation.
   */
  private int maxIntegerDigitsExponent;
172

173 174
  /** Defines if the format string has a negative prefix or not. */
  private boolean hasNegativePrefix;
175

176 177
  /** Defines if the format string has a fractional pattern or not. */
  private boolean hasFractionalPattern;
178

179 180
  /** Stores a list of attributes for use by formatToCharacterIterator. */
  private ArrayList attributes = new ArrayList();
181

182
  /**
Tom Tromey committed
183 184 185
   * Constructs a <code>DecimalFormat</code> which uses the default
   * pattern and symbols.
   */
186
  public DecimalFormat()
Tom Tromey committed
187 188 189
  {
    this ("#,##0.###");
  }
190

Tom Tromey committed
191 192 193 194 195 196 197 198
  /**
   * 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.
   */
199
  public DecimalFormat(String pattern)
Tom Tromey committed
200
  {
201
    this (pattern, new DecimalFormatSymbols());
Tom Tromey committed
202 203 204 205 206
  }

  /**
   * Constructs a <code>DecimalFormat</code> using the given pattern
   * and formatting symbols.  This construction method is used to give
207
   * complete control over the formatting process.
Tom Tromey committed
208 209 210 211 212 213 214 215 216
   *
   * @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();
217 218
    applyPatternWithSymbols(pattern, nonLocalizedSymbols);
  }
219

220 221
  /**
   * Apply the given localized patern to the current DecimalFormat object.
222
   *
223 224 225 226 227 228 229
   * @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
230 231
  }

232 233
  /**
   * Apply the given localized pattern to the current DecimalFormat object.
234
   *
235 236 237 238 239
   * @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
240
  {
241 242 243 244 245 246 247 248
    applyPatternWithSymbols(pattern, nonLocalizedSymbols);
  }

  public Object clone()
  {
    DecimalFormat c = (DecimalFormat) super.clone();
    c.symbols = (DecimalFormatSymbols) symbols.clone();
    return c;
Tom Tromey committed
249 250 251 252 253 254 255 256 257 258
  }

  /**
   * 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>
259
   *
Tom Tromey committed
260
   * @param obj  the object (<code>null</code> permitted).
261
   *
Tom Tromey committed
262 263 264 265 266 267 268
   * @return A boolean.
   */
  public boolean equals(Object obj)
  {
    if (! (obj instanceof DecimalFormat))
      return false;
    DecimalFormat dup = (DecimalFormat) obj;
269
    return (decimalSeparatorAlwaysShown == dup.decimalSeparatorAlwaysShown
270
           && groupingUsed == dup.groupingUsed
271
           && groupingSeparatorInPattern == dup.groupingSeparatorInPattern
272
           && groupingSize == dup.groupingSize
Tom Tromey committed
273 274 275 276 277 278 279
           && multiplier == dup.multiplier
           && useExponentialNotation == dup.useExponentialNotation
           && minExponentDigits == dup.minExponentDigits
           && minimumIntegerDigits == dup.minimumIntegerDigits
           && maximumIntegerDigits == dup.maximumIntegerDigits
           && minimumFractionDigits == dup.minimumFractionDigits
           && maximumFractionDigits == dup.maximumFractionDigits
280 281 282 283 284 285 286 287
           && 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
288 289 290 291 292 293 294
           && equals(negativePrefix, dup.negativePrefix)
           && equals(negativeSuffix, dup.negativeSuffix)
           && equals(positivePrefix, dup.positivePrefix)
           && equals(positiveSuffix, dup.positiveSuffix)
           && symbols.equals(dup.symbols));
  }

295 296 297 298 299 300
  /**
   * Returns a hash code for this object.
   *
   * @return A hash code.
   */
  public int hashCode()
Tom Tromey committed
301
  {
302 303
    return toPattern().hashCode();
  }
304

305 306
  /**
   * Produce a formatted {@link String} representation of this object.
307 308
   * The passed object must be of type number.
   *
309
   * @param obj The {@link Number} to format.
310
   * @param sbuf The destination String; text will be appended to this String.
311 312 313 314
   * @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.
   */
315
  public final StringBuffer format(Object obj, StringBuffer sbuf, FieldPosition pos)
316 317
  {
    if (obj instanceof BigInteger)
Tom Tromey committed
318
      {
319 320 321
        BigDecimal decimal = new BigDecimal((BigInteger) obj);
        formatInternal(decimal, true, sbuf, pos);
        return sbuf;
Tom Tromey committed
322
      }
323
    else if (obj instanceof BigDecimal)
Tom Tromey committed
324
      {
325 326
        formatInternal((BigDecimal) obj, true, sbuf, pos);
        return sbuf;
Tom Tromey committed
327
      }
328

329 330
    return super.format(obj, sbuf, pos);
  }
331

332 333
  /**
   * Produce a formatted {@link String} representation of this double.
334
   *
335
   * @param number The double to format.
336
   * @param dest The destination String; text will be appended to this String.
337 338 339 340 341 342
   * @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,
343
                             FieldPosition fieldPos)
344 345 346
  {
    // special cases for double: NaN and negative or positive infinity
    if (Double.isNaN(number))
Tom Tromey committed
347
      {
348 349 350
        // 1. NaN
        String nan = symbols.getNaN();
        dest.append(nan);
351

352 353 354 355 356 357 358 359
        // 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
360
      }
361
    else if (Double.isInfinite(number))
Tom Tromey committed
362
      {
363 364 365 366 367
        // 2. Infinity
        if (number < 0)
          dest.append(this.negativePrefix);
        else
          dest.append(this.positivePrefix);
368

369
        dest.append(symbols.getInfinity());
370

371 372 373 374
        if (number < 0)
          dest.append(this.negativeSuffix);
        else
          dest.append(this.positiveSuffix);
375

376 377 378 379 380 381
        if ((fieldPos.getField() == INTEGER_FIELD ||
            fieldPos.getFieldAttribute() == NumberFormat.Field.INTEGER))
         {
           fieldPos.setBeginIndex(dest.length());
           fieldPos.setEndIndex(0);
         }
Tom Tromey committed
382 383 384
      }
    else
      {
385 386 387
        // get the number as a BigDecimal
        BigDecimal bigDecimal = new BigDecimal(String.valueOf(number));
        formatInternal(bigDecimal, false, dest, fieldPos);
Tom Tromey committed
388
      }
389

390
    return dest;
Tom Tromey committed
391 392
  }

393 394
  /**
   * Produce a formatted {@link String} representation of this long.
395
   *
396
   * @param number The long to format.
397
   * @param dest The destination String; text will be appended to this String.
398 399 400 401 402 403
   * @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
404
  {
405 406
    BigDecimal bigDecimal = new BigDecimal(String.valueOf(number));
    formatInternal(bigDecimal, true, dest, fieldPos);
Tom Tromey committed
407 408
    return dest;
  }
409

410 411 412
  /**
   * Return an <code>AttributedCharacterIterator</code> as a result of
   * the formatting of the passed {@link Object}.
413
   *
414
   * @return An {@link AttributedCharacterIterator}.
415
   * @throws NullPointerException if value is <code>null</code>.
416 417 418 419
   * @throws IllegalArgumentException if value is not an instance of
   * {@link Number}.
   */
  public AttributedCharacterIterator formatToCharacterIterator(Object value)
Tom Tromey committed
420
  {
421 422 423 424
    /*
     * This method implementation derives directly from the
     * ICU4J (http://icu.sourceforge.net/) library, distributed under MIT/X.
     */
425

426 427
    if (value == null)
      throw new NullPointerException("Passed Object is null");
428

429 430
    if (!(value instanceof Number)) throw new
      IllegalArgumentException("Cannot format given Object as a Number");
431

432 433 434
    StringBuffer text = new StringBuffer();
    attributes.clear();
    super.format(value, text, new FieldPosition(0));
Tom Tromey committed
435

436
    AttributedString as = new AttributedString(text.toString());
Tom Tromey committed
437

438 439
    // add NumberFormat field attributes to the AttributedString
    for (int i = 0; i < attributes.size(); i++)
Tom Tromey committed
440
      {
441 442
        FieldPosition pos = (FieldPosition) attributes.get(i);
        Format.Field attribute = pos.getFieldAttribute();
443

444 445
        as.addAttribute(attribute, attribute, pos.getBeginIndex(),
                        pos.getEndIndex());
Tom Tromey committed
446
      }
447

448 449
    // return the CharacterIterator from AttributedString
    return as.getIterator();
Tom Tromey committed
450
  }
451

Tom Tromey committed
452 453 454 455 456 457 458 459 460 461 462 463
  /**
   * 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();
  }
464

Tom Tromey committed
465 466
  /**
   * Returns a copy of the symbols used by this instance.
467
   *
Tom Tromey committed
468 469 470 471 472 473
   * @return A copy of the symbols.
   */
  public DecimalFormatSymbols getDecimalFormatSymbols()
  {
    return (DecimalFormatSymbols) symbols.clone();
  }
474

475 476 477 478
  /**
   * 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.
479
   *
480 481
   * The actual character used as grouping separator depends on the
   * locale and is defined by {@link DecimalFormatSymbols#getDecimalSeparator()}
482
   *
483 484 485
   * @return The interval used between a grouping separator and the next.
   */
  public int getGroupingSize()
Tom Tromey committed
486 487 488 489
  {
    return groupingSize;
  }

490 491
  /**
   * Gets the multiplier used in percent and similar formats.
492
   *
493 494 495
   * @return The multiplier used in percent and similar formats.
   */
  public int getMultiplier()
Tom Tromey committed
496 497 498
  {
    return multiplier;
  }
499

500 501
  /**
   * Gets the negative prefix.
502
   *
503 504 505
   * @return The negative prefix.
   */
  public String getNegativePrefix()
Tom Tromey committed
506 507 508 509
  {
    return negativePrefix;
  }

510 511
  /**
   * Gets the negative suffix.
512
   *
513 514 515
   * @return The negative suffix.
   */
  public String getNegativeSuffix()
Tom Tromey committed
516 517 518
  {
    return negativeSuffix;
  }
519

520 521
  /**
   * Gets the positive prefix.
522
   *
523 524 525
   * @return The positive prefix.
   */
  public String getPositivePrefix()
Tom Tromey committed
526 527 528
  {
    return positivePrefix;
  }
529

530 531
  /**
   * Gets the positive suffix.
532
   *
533 534 535
   * @return The positive suffix.
   */
  public String getPositiveSuffix()
Tom Tromey committed
536 537 538
  {
    return positiveSuffix;
  }
539

540 541 542 543
  public boolean isDecimalSeparatorAlwaysShown()
  {
    return decimalSeparatorAlwaysShown;
  }
544

Tom Tromey committed
545
  /**
546
   * Define if <code>parse(java.lang.String, java.text.ParsePosition)</code>
547 548
   * should return a {@link BigDecimal} or not.
   *
549
   * @param newValue
Tom Tromey committed
550
   */
551
  public void setParseBigDecimal(boolean newValue)
Tom Tromey committed
552
  {
553
    this.parseBigDecimal = newValue;
Tom Tromey committed
554
  }
555

556 557 558 559 560
  /**
   * 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>.
561
   *
562 563 564 565 566 567
   * @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
568
  {
569
    return this.parseBigDecimal;
Tom Tromey committed
570
  }
571

572 573
  /**
   * This method parses the specified string into a <code>Number</code>.
574
   *
575 576 577 578
   * 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.
579
   *
580 581 582 583 584 585
   * @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
586
  {
587 588 589 590
    // a special values before anything else
    // NaN
    if (str.contains(this.symbols.getNaN()))
      return Double.valueOf(Double.NaN);
591

592
    // this will be our final number
593
    CPStringBuilder number = new CPStringBuilder();
594

595 596
    // special character
    char minus = symbols.getMinusSign();
597

598 599
    // starting parsing position
    int start = pos.getIndex();
600 601

    // validate the string, it have to be in the
602 603 604 605
    // same form as the format string or parsing will fail
    String _negativePrefix = (this.negativePrefix.compareTo("") == 0
                              ? minus + positivePrefix
                              : this.negativePrefix);
606

607 608 609 610
    // 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();
611

612 613
    boolean isNegative = str.startsWith(_negativePrefix);
    boolean isPositive = str.startsWith(positivePrefix);
614

615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
    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
633
      {
634 635
        start += _negativePrefix.length();
        isPositive = false;
Tom Tromey committed
636
      }
637
    else if (isPositive)
Tom Tromey committed
638
      {
639 640
        start += positivePrefix.length();
        isNegative = false;
Tom Tromey committed
641 642 643
      }
    else
      {
644 645
        pos.setErrorIndex(start);
        return null;
Tom Tromey committed
646
      }
647

648 649 650
    // other special characters used by the parser
    char decimalSeparator = symbols.getDecimalSeparator();
    char zero = symbols.getZeroDigit();
651 652
    char exponent = symbols.getExponential();

653 654
    // stop parsing position in the string
    int stop = start + this.maximumIntegerDigits + maximumFractionDigits + 2;
655

Tom Tromey committed
656
    if (useExponentialNotation)
657
      stop += minExponentDigits + 1;
658

659
    boolean inExponent = false;
Tom Tromey committed
660

661 662 663
    // correct the size of the end parsing flag
    int len = str.length();
    if (len < stop) stop = len;
664
    char groupingSeparator = symbols.getGroupingSeparator();
665

666 667
    int i = start;
    while (i < stop)
Tom Tromey committed
668
      {
669 670
        char ch = str.charAt(i);
        i++;
671

672 673 674 675 676 677
        if (ch >= zero && ch <= (zero + 9))
          {
            number.append(ch);
          }
        else if (this.parseIntegerOnly)
          {
678
            i--;
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
            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
695 696 697 698 699 700 701 702 703 704 705 706
              {
                i--;
                break;
              }
          }
        else
          {
            if (!groupingUsed || ch != groupingSeparator)
              {
                i--;
                break;
              }
707
          }
Tom Tromey committed
708 709
      }

710 711 712
    // 2nd special case: infinity
    // XXX: need to be tested
    if (str.contains(symbols.getInfinity()))
Tom Tromey committed
713
      {
714
        int inf = str.indexOf(symbols.getInfinity());
715
        pos.setIndex(inf);
716

717 718 719 720
        // FIXME: ouch, this is really ugly and lazy code...
        if (this.parseBigDecimal)
          {
            if (isNegative)
721
              return BigDecimal.valueOf(Double.NEGATIVE_INFINITY);
722

723
            return BigDecimal.valueOf(Double.POSITIVE_INFINITY);
724
          }
725

726
        if (isNegative)
727
          return Double.valueOf(Double.NEGATIVE_INFINITY);
Tom Tromey committed
728

729
        return Double.valueOf(Double.POSITIVE_INFINITY);
Tom Tromey committed
730
      }
731

732 733
    // no number...
    if (i == start || number.length() == 0)
Tom Tromey committed
734
      {
735 736
        pos.setErrorIndex(i);
        return null;
Tom Tromey committed
737 738
      }

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

745 746
    positiveLen = positiveSuffix.length();
    negativeLen = negativeSuffix.length();
747

748
    if (isNegative && !hasNegativeSuffix)
Tom Tromey committed
749
      {
750 751
        pos.setErrorIndex(i);
        return null;
Tom Tromey committed
752
      }
753
    else if (hasNegativeSuffix &&
754 755
             !positiveEqualsNegative &&
             (negativeLen > positiveLen))
Tom Tromey committed
756
      {
757
        isNegative = true;
Tom Tromey committed
758
      }
759
    else if (!hasPositiveSuffix)
Tom Tromey committed
760
      {
761 762
        pos.setErrorIndex(i);
        return null;
Tom Tromey committed
763
      }
764

765
    if (isNegative) number.insert(0, '-');
766

767
    pos.setIndex(i);
768

769 770 771 772
    // now we handle the return type
    BigDecimal bigDecimal = new BigDecimal(number.toString());
    if (this.parseBigDecimal)
      return bigDecimal;
773

774 775
    // want integer?
    if (this.parseIntegerOnly)
776
      return Long.valueOf(bigDecimal.longValue());
777 778 779

    // 3th special case -0.0
    if (isNegative && (bigDecimal.compareTo(BigDecimal.ZERO) == 0))
780
      return Double.valueOf(-0.0);
781

782
    try
Tom Tromey committed
783
      {
784 785
        BigDecimal integer
          = bigDecimal.setScale(0, BigDecimal.ROUND_UNNECESSARY);
786
        return Long.valueOf(integer.longValue());
Tom Tromey committed
787
      }
788
    catch (ArithmeticException e)
Tom Tromey committed
789
      {
790
        return Double.valueOf(bigDecimal.doubleValue());
Tom Tromey committed
791 792 793 794 795 796 797
      }
  }

  /**
   * Sets the <code>Currency</code> on the
   * <code>DecimalFormatSymbols</code> used, which also sets the
   * currency symbols on those symbols.
798
   *
799 800
   * @param currency The new <code>Currency</code> on the
   * <code>DecimalFormatSymbols</code>.
Tom Tromey committed
801 802 803
   */
  public void setCurrency(Currency currency)
  {
804 805 806
    Currency current = symbols.getCurrency();
    if (current != currency)
      {
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
        String oldSymbol = symbols.getCurrencySymbol();
        int len = oldSymbol.length();
        symbols.setCurrency(currency);
        String newSymbol = symbols.getCurrencySymbol();
        int posPre = positivePrefix.indexOf(oldSymbol);
        if (posPre != -1)
          positivePrefix = positivePrefix.substring(0, posPre) +
            newSymbol + positivePrefix.substring(posPre+len);
        int negPre = negativePrefix.indexOf(oldSymbol);
        if (negPre != -1)
          negativePrefix = negativePrefix.substring(0, negPre) +
            newSymbol + negativePrefix.substring(negPre+len);
        int posSuf = positiveSuffix.indexOf(oldSymbol);
        if (posSuf != -1)
          positiveSuffix = positiveSuffix.substring(0, posSuf) +
            newSymbol + positiveSuffix.substring(posSuf+len);
        int negSuf = negativeSuffix.indexOf(oldSymbol);
        if (negSuf != -1)
          negativeSuffix = negativeSuffix.substring(0, negSuf) +
            newSymbol + negativeSuffix.substring(negSuf+len);
827
      }
Tom Tromey committed
828
  }
829

Tom Tromey committed
830
  /**
831
   * Sets the symbols used by this instance.  This method makes a copy of
Tom Tromey committed
832
   * the supplied symbols.
833
   *
Tom Tromey committed
834 835 836 837 838 839
   * @param newSymbols  the symbols (<code>null</code> not permitted).
   */
  public void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols)
  {
    symbols = (DecimalFormatSymbols) newSymbols.clone();
  }
840

841 842 843 844 845
  /**
   * 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.
846
   *
847 848 849 850
   * @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
851 852 853
  {
    decimalSeparatorAlwaysShown = newValue;
  }
854

855 856 857 858
  /**
   * 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>.
859
   *
860 861 862 863
   * @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
864 865 866
  {
    groupingSize = (byte) groupSize;
  }
867

868 869 870 871 872 873
  /**
   * 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.
874
   *
875 876 877
   * @param newValue The new maximum integer digits value.
   */
  public void setMaximumIntegerDigits(int newValue)
Tom Tromey committed
878
  {
879 880
    newValue = (newValue > 0) ? newValue : 0;
    super.setMaximumIntegerDigits(Math.min(newValue, DEFAULT_INTEGER_DIGITS));
Tom Tromey committed
881
  }
882

883 884 885 886 887 888
  /**
   * 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.
889
   *
890 891 892
   * @param newValue The new minimum integer digits value.
   */
  public void setMinimumIntegerDigits(int newValue)
Tom Tromey committed
893
  {
894 895
    newValue = (newValue > 0) ? newValue : 0;
    super.setMinimumIntegerDigits(Math.min(newValue,  DEFAULT_INTEGER_DIGITS));
Tom Tromey committed
896
  }
897

898 899 900 901 902 903
  /**
   * 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.
904
   *
905 906 907
   * @param newValue The new maximum fraction digits value.
   */
  public void setMaximumFractionDigits(int newValue)
Tom Tromey committed
908
  {
909 910
    newValue = (newValue > 0) ? newValue : 0;
    super.setMaximumFractionDigits(Math.min(newValue, DEFAULT_FRACTION_DIGITS));
Tom Tromey committed
911
  }
912

913 914 915 916 917 918
  /**
   * 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.
919
   *
920 921 922
   * @param newValue The new minimum fraction digits value.
   */
  public void setMinimumFractionDigits(int newValue)
Tom Tromey committed
923
  {
924 925
    newValue = (newValue > 0) ? newValue : 0;
    super.setMinimumFractionDigits(Math.min(newValue, DEFAULT_FRACTION_DIGITS));
Tom Tromey committed
926
  }
927

928 929 930 931
  /**
   * 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.
932
   *
933 934 935
   * @param newValue the new value for multiplier.
   */
  public void setMultiplier(int newValue)
Tom Tromey committed
936 937 938
  {
    multiplier = newValue;
  }
939

940 941
  /**
   * Sets the negative prefix.
942
   *
943 944 945
   * @param newValue The new negative prefix.
   */
  public void setNegativePrefix(String newValue)
Tom Tromey committed
946 947 948 949
  {
    negativePrefix = newValue;
  }

950 951
  /**
   * Sets the negative suffix.
952
   *
953 954 955
   * @param newValue The new negative suffix.
   */
  public void setNegativeSuffix(String newValue)
Tom Tromey committed
956 957 958
  {
    negativeSuffix = newValue;
  }
959

960 961
  /**
   * Sets the positive prefix.
962
   *
963 964 965
   * @param newValue The new positive prefix.
   */
  public void setPositivePrefix(String newValue)
Tom Tromey committed
966 967 968
  {
    positivePrefix = newValue;
  }
969

970 971
  /**
   * Sets the new positive suffix.
972
   *
973 974 975
   * @param newValue The new positive suffix.
   */
  public void setPositiveSuffix(String newValue)
Tom Tromey committed
976 977 978
  {
    positiveSuffix = newValue;
  }
979

980 981 982
  /**
   * This method returns a string with the formatting pattern being used
   * by this object. The string is localized.
983
   *
984 985 986 987 988 989 990
   * @return A localized <code>String</code> with the formatting pattern.
   * @see #toPattern()
   */
  public String toLocalizedPattern()
  {
    return computePattern(this.symbols);
  }
991

992 993 994
  /**
   * This method returns a string with the formatting pattern being used
   * by this object. The string is not localized.
995
   *
996 997 998 999 1000 1001 1002
   * @return A <code>String</code> with the formatting pattern.
   * @see #toLocalizedPattern()
   */
  public String toPattern()
  {
    return computePattern(nonLocalizedSymbols);
  }
1003

1004
  /* ***** private methods ***** */
1005

1006 1007 1008
  /**
   * This is an shortcut helper method used to test if two given strings are
   * equals.
1009
   *
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
   * @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);
  }
1021 1022


1023
  /* ****** PATTERN ****** */
1024

1025 1026 1027 1028 1029 1030
  /**
   * 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)
  {
1031
    CPStringBuilder buf = new CPStringBuilder ();
1032

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
    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');
1044

1045 1046
    return buf.toString();
  }
Tom Tromey committed
1047

1048 1049 1050
  /**
   * Quote special characters as defined by <code>patChars</code> in the
   * input string.
1051
   *
1052 1053 1054 1055
   * @param text
   * @param patChars
   * @return A StringBuffer with special characters quoted.
   */
1056
  private CPStringBuilder quoteFix(String text, String patChars)
Tom Tromey committed
1057
  {
1058
    CPStringBuilder buf = new CPStringBuilder();
1059

Tom Tromey committed
1060
    int len = text.length();
1061
    char ch;
Tom Tromey committed
1062 1063
    for (int index = 0; index < len; ++index)
      {
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
        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
1075
      }
1076

1077
    return buf;
Tom Tromey committed
1078
  }
1079

1080 1081 1082 1083 1084
  /**
   * Returns the format pattern, localized to follow the given
   * symbols.
   */
  private String computePattern(DecimalFormatSymbols symbols)
Tom Tromey committed
1085
  {
1086
    StringBuilder mainPattern = new StringBuilder();
1087

Tom Tromey committed
1088
    // We have to at least emit a zero for the minimum number of
1089
    // digits. Past that we need hash marks up to the grouping
Tom Tromey committed
1090
    // separator (and one beyond).
1091 1092
    int _groupingSize = groupingUsed ? groupingSize + 1: groupingSize;
    int totalDigits = Math.max(minimumIntegerDigits, _groupingSize);
1093

1094 1095 1096
    // if it is not in exponential notiation,
    // we always have a # prebended
    if (!useExponentialNotation) mainPattern.append(symbols.getDigit());
1097

1098 1099
    for (int i = 1; i < totalDigits - minimumIntegerDigits; i++)
      mainPattern.append(symbols.getDigit());
1100

1101 1102
    for (int i = totalDigits - minimumIntegerDigits; i < totalDigits; i++)
      mainPattern.append(symbols.getZeroDigit());
1103

Tom Tromey committed
1104
    if (groupingUsed)
1105 1106 1107 1108 1109
      {
        mainPattern.insert(mainPattern.length() - groupingSize,
                           symbols.getGroupingSeparator());
      }

Tom Tromey committed
1110
    // See if we need decimal info.
1111 1112 1113 1114 1115
    if (minimumFractionDigits > 0 || maximumFractionDigits > 0 ||
        decimalSeparatorAlwaysShown)
      {
        mainPattern.append(symbols.getDecimalSeparator());
      }
1116

Tom Tromey committed
1117
    for (int i = 0; i < minimumFractionDigits; ++i)
1118
      mainPattern.append(symbols.getZeroDigit());
1119

Tom Tromey committed
1120
    for (int i = minimumFractionDigits; i < maximumFractionDigits; ++i)
1121
      mainPattern.append(symbols.getDigit());
1122

Tom Tromey committed
1123 1124
    if (useExponentialNotation)
      {
1125
        mainPattern.append(symbols.getExponential());
1126

1127 1128
        for (int i = 0; i < minExponentDigits; ++i)
          mainPattern.append(symbols.getZeroDigit());
1129

1130 1131
        if (minExponentDigits == 0)
          mainPattern.append(symbols.getDigit());
Tom Tromey committed
1132
      }
1133

1134 1135
    // save the pattern
    String pattern = mainPattern.toString();
1136

1137 1138 1139 1140 1141
    // 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));
1142

1143
    if (hasNegativePrefix)
Tom Tromey committed
1144
      {
1145 1146 1147 1148
        mainPattern.append(symbols.getPatternSeparator());
        mainPattern.append(quoteFix(negativePrefix, patternChars));
        mainPattern.append(pattern);
        mainPattern.append(quoteFix(negativeSuffix, patternChars));
Tom Tromey committed
1149
      }
1150

1151
    // finally, return the pattern string
Tom Tromey committed
1152 1153
    return mainPattern.toString();
  }
1154

1155
  /* ****** FORMAT PARSING ****** */
1156

1157 1158 1159
  /**
   * Scan the input string and define a pattern suitable for use
   * with this decimal format.
1160
   *
1161 1162 1163 1164 1165
   * @param pattern
   * @param symbols
   */
  private void applyPatternWithSymbols(String pattern,
                                       DecimalFormatSymbols symbols)
Tom Tromey committed
1166
  {
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
    // 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.
1178

1179 1180 1181
    // Restore default values. Most of these will be overwritten
    // but we want to be sure that nothing is left out.
    setDefaultValues();
1182

1183 1184 1185 1186 1187 1188 1189 1190
    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;
1191

1192 1193 1194 1195 1196
        // FIXME: ...and these values may not be valid in all locales
        this.minExponentDigits = 0;
        this.showDecimalSeparator = true;
        this.groupingUsed = true;
        this.groupingSize = 3;
1197

1198 1199
        return;
      }
1200

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
    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;
      }
1216

1217 1218 1219 1220
    // 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!");
1221

1222 1223 1224
    if (start < len) start = scanExponent(pattern, symbols, start);
    if (start < len) start = scanFix(pattern, symbols, start, false);
    if (start < len) scanNegativePattern(pattern, symbols, start);
1225

1226 1227 1228 1229 1230 1231 1232
    if (useExponentialNotation &&
        (maxIntegerDigitsExponent > minimumIntegerDigits) &&
        (maxIntegerDigitsExponent > 1))
      {
        minimumIntegerDigits = 1;
        exponentRound = maxIntegerDigitsExponent;
      }
1233

1234 1235
    if (useExponentialNotation)
      maximumIntegerDigits = maxIntegerDigitsExponent;
1236

1237 1238 1239 1240 1241
    if (!this.hasFractionalPattern && this.showDecimalSeparator == true)
      {
        this.decimalSeparatorAlwaysShown = true;
      }
  }
1242

1243 1244 1245
  /**
   * Scans for the prefix or suffix portion of the pattern string.
   * This method handles the positive subpattern of the pattern string.
1246
   *
1247 1248 1249 1250 1251 1252
   * @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)
  {
1253
    CPStringBuilder buffer = new CPStringBuilder();
1254

1255 1256 1257 1258 1259 1260 1261 1262
    // 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();
1263

1264 1265 1266
    // other special characters, cached here to avoid method calls later
    char percent = sourceSymbols.getPercent();
    char permille = sourceSymbols.getPerMill();
1267

1268
    String currencySymbol = this.symbols.getCurrencySymbol();
1269

1270
    boolean quote = false;
1271

1272 1273 1274 1275 1276 1277 1278 1279
    char ch = pattern.charAt(start);
    if (ch == patternSeparator)
      {
        // negative subpattern
        this.hasNegativePrefix = true;
        ++start;
        return start;
      }
1280

1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
    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);
              }
1295

1296 1297 1298 1299
            this.hasNegativePrefix = true;
            ++i;
            break;
          }
1300

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
        // 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;
          }
1317

1318 1319 1320 1321 1322 1323
        if (ch == '\u00A4')
          {
            // CURRENCY
            currencySymbol = this.symbols.getCurrencySymbol();

            // if \u00A4 is doubled, we use the international currency symbol
1324
            if ((i + 1) < len && pattern.charAt(i + 1) == '\u00A4')
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
              {
                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
1348
            if ((i + 1) < len && pattern.charAt(i + 1) == '\'')
1349
              {
1350
                // we need to add ' to the buffer
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
                buffer.append(ch);
                i++;
              }
            else
              {
                quote = !quote;
                continue;
              }
          }
        else
          {
            buffer.append(ch);
          }
      }
1365

1366 1367 1368 1369 1370 1371 1372 1373 1374
    if (prefix)
      {
        this.positivePrefix = buffer.toString();
        this.negativePrefix = minus + "" + positivePrefix;
      }
    else
      {
        this.positiveSuffix = buffer.toString();
      }
1375

1376 1377
    return i;
  }
1378

1379 1380 1381 1382
  /**
   * Scan the given string for number patterns, starting
   * from <code>start</code>.
   * This method searches the integer part of the pattern only.
1383
   *
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
   * @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();
1398

1399 1400 1401
    // count the number of zeroes in the pattern
    // this number defines the minum digits in the integer portion
    int zeros = 0;
1402

1403 1404
    // count the number of digits used in grouping
    int _groupingSize = 0;
1405

1406
    this.maxIntegerDigitsExponent = 0;
1407

1408
    boolean intPartTouched = false;
1409

1410 1411 1412 1413 1414 1415
    char ch;
    int len = pattern.length();
    int i;
    for (i = start; i < len; i++)
      {
        ch = pattern.charAt(i);
1416

1417 1418 1419
        // break on decimal separator or exponent or pattern separator
        if (ch == decimalSeparator || ch == exponent)
          break;
1420

1421 1422 1423
        if (this.hasNegativePrefix && ch == patternSeparator)
          throw new IllegalArgumentException("Invalid pattern found: "
                                             + start);
1424

1425 1426 1427 1428 1429 1430 1431 1432
        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);
1433

1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
            _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;
          }
      }
1457

1458 1459
    if (groupingSeparatorInPattern) this.groupingSize = (byte) _groupingSize;
    this.minimumIntegerDigits = zeros;
1460

1461 1462 1463 1464 1465
    // 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
1466

1467 1468
    return i;
  }
1469

1470 1471 1472 1473
  /**
   * Scan the given string for number patterns, starting
   * from <code>start</code>.
   * This method searches the fractional part of the pattern only.
1474
   *
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
   * @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();
1490

1491 1492 1493 1494 1495 1496 1497 1498 1499
    // 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;
      }
1500

1501
    ++start;
1502

1503
    this.hasFractionalPattern = true;
1504

1505 1506
    this.minimumFractionDigits = 0;
    int digits = 0;
1507

1508 1509 1510 1511 1512
    int len = pattern.length();
    int i;
    for (i = start; i < len; i++)
      {
        ch = pattern.charAt(i);
1513

1514 1515 1516
        // we hit the exponential or negative subpattern
        if (ch == exponent || ch == patternSeparator)
          break;
1517

1518 1519 1520 1521
        // pattern error
        if (ch == groupingSeparator || ch == decimalSeparator) throw new
          IllegalArgumentException("unexpected character '" + ch + "' " +
                                   "in fractional subpattern. Position: " + i);
1522

1523 1524 1525 1526 1527 1528 1529 1530 1531
        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);
1532

1533 1534 1535 1536 1537 1538 1539 1540
            this.minimumFractionDigits++;
          }
        else
          {
            // we are in the suffix section of pattern
            break;
          }
      }
1541

1542
    if (i == start) this.hasFractionalPattern = false;
1543

1544 1545
    this.maximumFractionDigits = this.minimumFractionDigits + digits;
    this.showDecimalSeparator = true;
1546

1547 1548
    return i;
  }
1549

1550 1551 1552 1553
  /**
   * Scan the given string for number patterns, starting
   * from <code>start</code>.
   * This method searches the expoential part of the pattern only.
1554
   *
1555 1556 1557 1558 1559 1560 1561
   * @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
1562
  {
1563 1564 1565 1566 1567
    char digit = symbols.getDigit();
    char zero = symbols.getZeroDigit();
    char groupingSeparator = symbols.getGroupingSeparator();
    char decimalSeparator = symbols.getDecimalSeparator();
    char exponent = symbols.getExponential();
1568

1569
    char ch = pattern.charAt(start);
1570

1571 1572 1573 1574 1575
    if (ch == decimalSeparator)
      {
        // ignore dots
        ++start;
      }
1576

1577 1578 1579 1580 1581
    if (ch != exponent)
      {
        this.useExponentialNotation = false;
        return start;
      }
1582

1583
    ++start;
1584

1585
    this.minExponentDigits = 0;
1586

1587 1588 1589 1590 1591
    int len = pattern.length();
    int i;
    for (i = start; i < len; i++)
      {
        ch = pattern.charAt(i);
1592

1593 1594
        if (ch == groupingSeparator || ch == decimalSeparator ||
            ch == digit || ch == exponent) throw new
1595
        IllegalArgumentException("unexpected character '" + ch + "' " +
1596
                                 "in exponential subpattern. Position: " + i);
1597

1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
        if (ch == zero)
          {
            this.minExponentDigits++;
          }
        else
          {
            // any character other than zero is an exit point
            break;
          }
      }
1608 1609 1610

    this.useExponentialNotation = true;

1611 1612
    return i;
  }
1613

1614 1615 1616 1617 1618
  /**
   * 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.
1619
   *
1620 1621 1622 1623 1624 1625 1626
   * @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)
  {
1627
    StringBuilder buffer = new StringBuilder();
1628

1629 1630 1631 1632 1633 1634 1635 1636
    // 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();
1637

1638 1639 1640
    // other special charcaters, cached here to avoid method calls later
    char percent = sourceSymbols.getPercent();
    char permille = sourceSymbols.getPerMill();
1641

1642 1643
    String CURRENCY_SYMBOL = this.symbols.getCurrencySymbol();
    String currencySymbol = CURRENCY_SYMBOL;
1644

1645 1646
    boolean quote = false;
    boolean prefixDone = false;
1647

1648 1649
    int len = pattern.length();
    if (len > 0) this.hasNegativePrefix = true;
1650

1651 1652 1653 1654 1655 1656
    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 + "' " +
1657
                                   "in negative subpattern.");
1658 1659
        start++;
      }
1660

1661 1662 1663 1664
    int i;
    for (i = start; i < len; i++)
      {
        ch = pattern.charAt(i);
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
        // 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;
1702

1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
            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
1720
            if ((i + 1) < len && pattern.charAt(i + 1) == '\'')
1721
              {
1722
                // we need to add ' to the buffer
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
                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);
          }
      }
1742

1743 1744 1745 1746 1747
    if (prefixDone)
      this.negativeSuffix = buffer.toString();
    else
      this.negativePrefix = buffer.toString();
  }
1748

1749
  /* ****** FORMATTING ****** */
1750

1751 1752
  /**
   * Handles the real formatting.
1753
   *
1754 1755 1756 1757 1758 1759
   * 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.
1760
   *
1761 1762 1763 1764 1765 1766 1767 1768
   * @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)
1769
  {
1770 1771 1772 1773 1774 1775 1776 1777
    // 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);
1778

1779
    int _multiplier = this.multiplier;
1780

1781 1782
    // used to track attribute starting position for each attribute
    int attributeStart = -1;
1783

1784 1785 1786 1787 1788 1789
    // 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();
1790

1791 1792
        // append the negative prefix to the string
        dest.append(negativePrefix);
1793

1794 1795 1796
        // once got the negative prefix, we can use
        // the absolute value.
        number = number.abs();
1797

1798
        _multiplier = negativePatternMultiplier;
1799

1800 1801 1802 1803 1804 1805 1806
        addAttribute(Field.SIGN, attributeStart, dest.length());
      }
    else
      {
        // not negative, use the positive prefix
        dest.append(positivePrefix);
      }
1807

1808 1809 1810 1811 1812
    // these are used ot update the field position
    int beginIndexInt = dest.length();
    int endIndexInt = 0;
    int beginIndexFract = 0;
    int endIndexFract = 0;
1813

1814
    // compute the multiplier to use with percent and similar
1815
    number = number.multiply(BigDecimal.valueOf(_multiplier));
1816

1817 1818 1819 1820 1821 1822 1823 1824 1825
    // 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;
      }
1826

1827 1828 1829 1830 1831
    //  get the absolute number
    number = number.abs();

    // the scaling to use while formatting this number
    int scale = this.maximumFractionDigits;
1832

1833 1834 1835 1836
    // this is the actual number we will use
    // it is corrected later on to handle exponential
    // notation, if needed
    long exponent = 0;
1837

1838 1839 1840 1841 1842
    // are we using exponential notation?
    if (this.useExponentialNotation)
      {
        exponent = getExponent(number);
        number = number.movePointLeft((int) exponent);
1843

1844 1845 1846 1847 1848 1849
        // 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;
      }
1850

1851 1852 1853 1854 1855 1856
    // 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();
1857

1858 1859
    String intPart = null;
    String fractPart = null;
1860

1861 1862 1863 1864 1865
    // 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);
1866

1867 1868 1869 1870 1871 1872
    // strip the decimal portion
    int dot = plain.indexOf('.');
    if (dot > -1)
      {
        intPart = plain.substring(0, dot);
        dot++;
1873

1874 1875 1876 1877 1878 1879 1880 1881 1882
        if (useExponentialNotation)
          fractPart = plain.substring(dot, dot + scale);
        else
          fractPart = plain.substring(dot);
      }
    else
      {
        intPart = plain;
      }
1883

1884 1885 1886
    // used in various places later on
    int intPartLen = intPart.length();
    endIndexInt = intPartLen;
1887

1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
    // 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.
1904

1905 1906 1907 1908 1909 1910 1911 1912 1913
        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);
1914

1915 1916 1917 1918
        // remove from the string the number in excess
        // use only latest digits
        intPart = intPart.substring(intPartLen - canary);
        endIndexInt = intPart.length() + 1;
1919

1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
        // 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);
          }
      }
1930

1931 1932
    // add the INTEGER attribute
    addAttribute(Field.INTEGER, attributeStart, dest.length());
1933

1934 1935 1936 1937 1938 1939 1940
    // ...update field position, if needed, and return...
    if ((fieldPos.getField() == INTEGER_FIELD ||
        fieldPos.getFieldAttribute() == NumberFormat.Field.INTEGER))
      {
        fieldPos.setBeginIndex(beginIndexInt);
        fieldPos.setEndIndex(endIndexInt);
      }
1941

1942
    handleFractionalPart(dest, fractPart, fieldPos, isLong);
1943

1944 1945 1946 1947
    // and the exponent
    if (this.useExponentialNotation)
      {
        attributeStart = dest.length();
1948

1949
        dest.append(symbols.getExponential());
1950

1951 1952
        addAttribute(Field.EXPONENT_SYMBOL, attributeStart, dest.length());
        attributeStart = dest.length();
1953

1954 1955 1956 1957
        if (exponent < 0)
          {
            dest.append(symbols.getMinusSign());
            exponent = -exponent;
1958

1959 1960
            addAttribute(Field.EXPONENT_SIGN, attributeStart, dest.length());
          }
1961

1962
        attributeStart = dest.length();
1963

1964 1965
        String exponentString = String.valueOf(exponent);
        int exponentLength = exponentString.length();
1966

1967 1968
        for (int i = 0; i < minExponentDigits - exponentLength; i++)
          dest.append(symbols.getZeroDigit());
1969

1970 1971
        for (int i = 0; i < exponentLength; ++i)
          dest.append(exponentString.charAt(i));
1972

1973 1974
        addAttribute(Field.EXPONENT, attributeStart, dest.length());
      }
1975

1976 1977 1978 1979 1980 1981
    // now include the suffixes...
    if (isNegative)
      {
        dest.append(negativeSuffix);
      }
    else
Tom Tromey committed
1982
      {
1983
        dest.append(positiveSuffix);
Tom Tromey committed
1984 1985 1986
      }
  }

1987 1988 1989
  /**
   * Add to the input buffer the result of formatting the fractional
   * portion of the number.
1990
   *
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
   * @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;
2002

2003 2004 2005 2006 2007 2008
    if (this.decimalSeparatorAlwaysShown  ||
         ((!isLong || this.useExponentialNotation) &&
           this.showDecimalSeparator && this.maximumFractionDigits > 0) ||
        this.minimumFractionDigits > 0)
      {
        dotStart = dest.length();
2009

2010 2011 2012 2013
        if (this.useCurrencySeparator)
          dest.append(symbols.getMonetaryDecimalSeparator());
        else
          dest.append(symbols.getDecimalSeparator());
2014

2015 2016 2017
        dotEnd = dest.length();
        addDecimal = true;
      }
2018

2019 2020 2021 2022
    // now handle the fraction portion of the number
    int fractStart = 0;
    int fractEnd = 0;
    boolean addFractional = false;
2023

2024 2025 2026 2027 2028 2029
    if ((!isLong || this.useExponentialNotation)
        && this.maximumFractionDigits > 0
        || this.minimumFractionDigits > 0)
      {
        fractStart = dest.length();
        fractEnd = fractStart;
2030

2031
        int digits = this.minimumFractionDigits;
2032

2033 2034 2035 2036 2037 2038
        if (this.useExponentialNotation)
          {
            digits = (this.minimumIntegerDigits + this.minimumFractionDigits)
              - dest.length();
            if (digits < 0) digits = 0;
          }
2039

2040
        fractPart = adjustTrailingZeros(fractPart, digits);
2041

2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
        // 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;
          }
2052

2053 2054 2055 2056
        if (!allZeros || (minimumFractionDigits > 0))
          {
            appendDigit(fractPart, dest, false);
            fractEnd = dest.length();
2057

2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
            addDecimal = true;
            addFractional = true;
          }
        else if (!this.decimalSeparatorAlwaysShown)
          {
            dest.deleteCharAt(dest.length() - 1);
            addDecimal = false;
          }
        else
          {
            fractEnd = dest.length();
            addFractional = true;
          }
      }
2072

2073 2074
    if (addDecimal)
      addAttribute(Field.DECIMAL_SEPARATOR, dotStart, dotEnd);
2075

2076 2077
    if (addFractional)
      addAttribute(Field.FRACTION, fractStart, fractEnd);
2078

2079 2080 2081 2082 2083 2084 2085
    if ((fieldPos.getField() == FRACTION_FIELD ||
        fieldPos.getFieldAttribute() == NumberFormat.Field.FRACTION))
      {
        fieldPos.setBeginIndex(fractStart);
        fieldPos.setEndIndex(fractEnd);
      }
  }
2086

2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
  /**
   * 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();
2097

2098 2099 2100 2101 2102 2103 2104 2105
    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);
2106

2107 2108
        dest.append(ch);
      }
2109

2110 2111 2112 2113 2114 2115
    // special case, that requires adding an additional separator
    if (this.groupingSeparatorInPattern &&
        (this.groupingUsed && this.groupingSize != 0) &&
        (gPos % groupingSize == 0))
      dest.append(gSeparator);
  }
2116

2117 2118
  /**
   * Append src to <code>dest</code>.
2119
   *
2120 2121 2122 2123 2124 2125 2126
   * 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';
2127

2128 2129
    int ch;
    char gSeparator = symbols.getGroupingSeparator();
2130

2131 2132 2133 2134 2135 2136 2137
    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
2138

2139 2140 2141
        dest.append((char) (zero + ch));
      }
  }
2142

Tom Tromey committed
2143
  /**
2144 2145 2146 2147
   * 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
2148
   */
2149
  private long getExponent(BigDecimal number)
Tom Tromey committed
2150
  {
2151
    long exponent = 0;
2152

2153 2154 2155 2156
    if (number.signum() > 0)
      {
        double _number = number.doubleValue();
        exponent = (long) Math.floor (Math.log10(_number));
2157

2158 2159
        // get the right value for the exponent
        exponent = exponent - (exponent % this.exponentRound);
2160

2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
        // 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;
      }
2171

2172 2173
    return exponent;
  }
2174

2175 2176 2177 2178 2179
  /**
   * 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.
2180
   *
2181 2182 2183
   * 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.
2184
   *
2185 2186 2187 2188 2189 2190
   * @param src The string with the correct number of zeros.
   */
  private String adjustTrailingZeros(String src, int minimumDigits)
  {
    int len = src.length();
    String result;
2191

2192 2193
    // remove all trailing zero
    if (len > minimumDigits)
Tom Tromey committed
2194
      {
2195
        int zeros = 0;
2196 2197 2198 2199 2200 2201 2202
        for (int i = len - 1; i > minimumDigits; i--)
          {
            if (src.charAt(i) == '0')
              ++zeros;
            else
              break;
          }
2203
        result =  src.substring(0, len - zeros);
Tom Tromey committed
2204
      }
2205 2206 2207
    else
      {
        char zero = symbols.getZeroDigit();
2208
        CPStringBuilder _result = new CPStringBuilder(src);
2209 2210 2211 2212 2213 2214
        for (int i = len; i < minimumDigits; i++)
          {
            _result.append(zero);
          }
        result = _result.toString();
      }
2215

2216
    return result;
Tom Tromey committed
2217
  }
2218

2219 2220
  /**
   * Adds an attribute to the attributes list.
2221
   *
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231
   * @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.
     */
2232

2233 2234 2235 2236 2237
    FieldPosition pos = new FieldPosition(field);
    pos.setBeginIndex(begin);
    pos.setEndIndex(end);
    attributes.add(pos);
  }
2238

2239 2240 2241 2242 2243 2244 2245 2246 2247
  /**
   * 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.
2248

2249 2250 2251 2252
    this.negativePrefix = String.valueOf(symbols.getMinusSign());
    this.negativeSuffix = "";
    this.positivePrefix = "";
    this.positiveSuffix = "";
2253

2254 2255 2256
    this.multiplier = 1;
    this.negativePatternMultiplier = 1;
    this.exponentRound = 1;
2257

2258
    this.hasNegativePrefix = false;
2259

2260 2261 2262 2263 2264
    this.minimumIntegerDigits = 1;
    this.maximumIntegerDigits = DEFAULT_INTEGER_DIGITS;
    this.minimumFractionDigits = 0;
    this.maximumFractionDigits = DEFAULT_FRACTION_DIGITS;
    this.minExponentDigits = 0;
2265

2266
    this.groupingSize = 0;
2267

2268 2269 2270 2271 2272
    this.decimalSeparatorAlwaysShown = false;
    this.showDecimalSeparator = false;
    this.useExponentialNotation = false;
    this.groupingUsed = false;
    this.groupingSeparatorInPattern = false;
2273

2274
    this.useCurrencySeparator = false;
2275

2276 2277
    this.hasFractionalPattern = false;
  }
Tom Tromey committed
2278
}