DecimalFormat.java 26 KB
Newer Older
1
/* DecimalFormat.java -- Formats and parses numbers
Tom Tromey committed
2
   Copyright (C) 1999, 2000, 2001, 2003 Free Software Foundation, Inc.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

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., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
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. */
Tom Tromey committed
37 38 39 40 41 42

package java.text;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
43 44
import java.io.ObjectInputStream;
import java.io.IOException;
Tom Tromey committed
45 46 47 48 49 50 51

/**
 * @author Tom Tromey <tromey@cygnus.com>
 * @date March 4, 1999
 */
/* Written using "Java Class Libraries", 2nd edition, plus online
 * API docs for JDK 1.2 from http://www.javasoft.com.
52
 * Status:  Believed complete and correct to 1.2.
Tom Tromey committed
53 54 55 56 57 58 59 60 61 62
 * Note however that the docs are very unclear about how format parsing
 * should work.  No doubt there are problems here.
 */
public class DecimalFormat extends NumberFormat
{
  // This is a helper for applyPatternWithSymbols.  It reads a prefix
  // or a suffix.  It can cause some side-effects.
  private final int scanFix (String pattern, int index, StringBuffer buf,
			     String patChars, DecimalFormatSymbols syms,
			     boolean is_suffix)
63 64 65 66 67 68 69 70 71 72
  {
    int len = pattern.length();
    buf.setLength(0);
    boolean multiplierSet = false;
    while (index < len)
      {
	char c = pattern.charAt(index);
	if (c == '\'' && index + 1 < len
	    && pattern.charAt(index + 1) == '\'')
	  {
Tom Tromey committed
73
	    buf.append(c);
74 75 76 77 78 79 80 81 82 83 84 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
	    ++index;
	  }
	else if (c == '\'' && index + 2 < len
		 && pattern.charAt(index + 2) == '\'')
	  {
	    buf.append(pattern.charAt(index + 1));
	    index += 2;
	  }
	else if (c == '\u00a4')
	  {
	    if (index + 1 < len && pattern.charAt(index + 1) == '\u00a4')
	      {
		buf.append(syms.getInternationalCurrencySymbol());
		++index;
	      }
	    else
	      buf.append(syms.getCurrencySymbol());
	  }
	else if (is_suffix && c == syms.getPercent())
	  {
	    if (multiplierSet)
	      throw new IllegalArgumentException ("multiplier already set " +
						  "- index: " + index);
	    multiplierSet = true;
	    multiplier = 100;
	    buf.append(c);
	  }
	else if (is_suffix && c == syms.getPerMill())
	  {
	    if (multiplierSet)
	      throw new IllegalArgumentException ("multiplier already set " +
						  "- index: " + index);
	    multiplierSet = true;
	    multiplier = 1000;
	    buf.append(c);
	  }
	else if (patChars.indexOf(c) != -1)
	  {
	    // This is a pattern character.
	    break;
	  }
	else
	  buf.append(c);
	++index;
      }
Tom Tromey committed
119

120 121
    return index;
  }
Tom Tromey committed
122 123 124 125 126

  // A helper which reads a number format.
  private final int scanFormat (String pattern, int index,
				String patChars, DecimalFormatSymbols syms,
				boolean is_positive)
127 128
  {
    int max = pattern.length();
Tom Tromey committed
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 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    int countSinceGroup = 0;
    int zeroCount = 0;
    boolean saw_group = false;

    //
    // Scan integer part.
    //
    while (index < max)
      {
	char c = pattern.charAt(index);

	if (c == syms.getDigit())
	  {
	    if (zeroCount > 0)
	      throw new IllegalArgumentException ("digit mark following " +
						  "zero - index: " + index);
	    ++countSinceGroup;
	  }
	else if (c == syms.getZeroDigit())
	  {
	    ++zeroCount;
	    ++countSinceGroup;
	  }
	else if (c == syms.getGroupingSeparator())
	  {
	    countSinceGroup = 0;
	    saw_group = true;
	  }
	else
	  break;

	++index;
      }

    // We can only side-effect when parsing the positive format.
    if (is_positive)
      {
	groupingUsed = saw_group;
	groupingSize = (byte) countSinceGroup;
	minimumIntegerDigits = zeroCount;
      }

    // Early termination.
    if (index == max || pattern.charAt(index) == syms.getGroupingSeparator())
      {
	if (is_positive)
	  decimalSeparatorAlwaysShown = false;
	return index;
      }

    if (pattern.charAt(index) == syms.getDecimalSeparator())
      {
	++index;

	//
	// Scan fractional part.
	//
	int hashCount = 0;
	zeroCount = 0;
	while (index < max)
	  {
	    char c = pattern.charAt(index);
	    if (c == syms.getZeroDigit())
	      {
		if (hashCount > 0)
		  throw new IllegalArgumentException ("zero mark " +
						      "following digit - index: " + index);
Tom Tromey committed
197
		++zeroCount;
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
	      }
	    else if (c == syms.getDigit())
	      {
		++hashCount;
	      }
	    else if (c != syms.getExponential()
		     && c != syms.getPatternSeparator()
		     && patChars.indexOf(c) != -1)
	      throw new IllegalArgumentException ("unexpected special " +
						  "character - index: " + index);
	    else
	      break;

	    ++index;
	  }

	if (is_positive)
	  {
	    maximumFractionDigits = hashCount + zeroCount;
	    minimumFractionDigits = zeroCount;
	  }

	if (index == max)
	  return index;
      }

    if (pattern.charAt(index) == syms.getExponential())
      {
	//
	// Scan exponential format.
	//
	zeroCount = 0;
	++index;
	while (index < max)
	  {
	    char c = pattern.charAt(index);
	    if (c == syms.getZeroDigit())
	      ++zeroCount;
	    else if (c == syms.getDigit())
	      {
		if (zeroCount > 0)
		  throw new
		    IllegalArgumentException ("digit mark following zero " +
					      "in exponent - index: " +
					      index);
	      }
	    else if (patChars.indexOf(c) != -1)
	      throw new IllegalArgumentException ("unexpected special " +
						  "character - index: " +
						  index);
	    else
	      break;

	    ++index;
	  }

	if (is_positive)
	  {
	    useExponentialNotation = true;
	    minExponentDigits = (byte) zeroCount;
	  }
      }

    return index;
  }
Tom Tromey committed
263 264 265 266

  // This helper function creates a string consisting of all the
  // characters which can appear in a pattern and must be quoted.
  private final String patternChars (DecimalFormatSymbols syms)
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
  {
    StringBuffer buf = new StringBuffer ();
    buf.append(syms.getDecimalSeparator());
    buf.append(syms.getDigit());
    buf.append(syms.getExponential());
    buf.append(syms.getGroupingSeparator());
    // Adding this one causes pattern application to fail.
    // Of course, omitting is causes toPattern to fail.
    // ... but we already have bugs there.  FIXME.
    // buf.append(syms.getMinusSign());
    buf.append(syms.getPatternSeparator());
    buf.append(syms.getPercent());
    buf.append(syms.getPerMill());
    buf.append(syms.getZeroDigit());
    buf.append('\u00a4');
    return buf.toString();
  }
Tom Tromey committed
284 285 286

  private final void applyPatternWithSymbols (String pattern,
					      DecimalFormatSymbols syms)
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
  {
    // Initialize to the state the parser expects.
    negativePrefix = "";
    negativeSuffix = "";
    positivePrefix = "";
    positiveSuffix = "";
    decimalSeparatorAlwaysShown = false;
    groupingSize = 0;
    minExponentDigits = 0;
    multiplier = 1;
    useExponentialNotation = false;
    groupingUsed = false;
    maximumFractionDigits = 0;
    maximumIntegerDigits = 309;
    minimumFractionDigits = 0;
    minimumIntegerDigits = 1;

    StringBuffer buf = new StringBuffer ();
    String patChars = patternChars (syms);

    int max = pattern.length();
    int index = scanFix (pattern, 0, buf, patChars, syms, false);
    positivePrefix = buf.toString();

    index = scanFormat (pattern, index, patChars, syms, true);

    index = scanFix (pattern, index, buf, patChars, syms, true);
    positiveSuffix = buf.toString();

    if (index == pattern.length())
      {
	// No negative info.
	negativePrefix = null;
	negativeSuffix = null;
      }
    else
      {
	if (pattern.charAt(index) != syms.getPatternSeparator())
	  throw new IllegalArgumentException ("separator character " +
					      "expected - index: " + index);

	index = scanFix (pattern, index + 1, buf, patChars, syms, false);
	negativePrefix = buf.toString();

	// We parse the negative format for errors but we don't let
	// it side-effect this object.
	index = scanFormat (pattern, index, patChars, syms, false);

	index = scanFix (pattern, index, buf, patChars, syms, true);
	negativeSuffix = buf.toString();

	if (index != pattern.length())
	  throw new IllegalArgumentException ("end of pattern expected " +
					      "- index: " + index);
      }
  }
Tom Tromey committed
343

344
  public void applyLocalizedPattern (String pattern)
345 346 347 348 349 350 351
  {
    // JCL p. 638 claims this throws a ParseException but p. 629
    // contradicts this.  Empirical tests with patterns of "0,###.0"
    // and "#.#.#" corroborate the p. 629 statement that an
    // IllegalArgumentException is thrown.
    applyPatternWithSymbols (pattern, symbols);
  }
Tom Tromey committed
352

353
  public void applyPattern (String pattern)
354 355 356 357 358 359 360
  {
    // JCL p. 638 claims this throws a ParseException but p. 629
    // contradicts this.  Empirical tests with patterns of "0,###.0"
    // and "#.#.#" corroborate the p. 629 statement that an
    // IllegalArgumentException is thrown.
    applyPatternWithSymbols (pattern, nonLocalizedSymbols);
  }
Tom Tromey committed
361 362

  public Object clone ()
363
  {
364 365 366
    DecimalFormat c = (DecimalFormat) super.clone ();
    c.symbols = (DecimalFormatSymbols) symbols.clone ();
    return c;
367
  }
Tom Tromey committed
368 369

  public DecimalFormat ()
370 371 372
  {
    this ("#,##0.###");
  }
Tom Tromey committed
373 374

  public DecimalFormat (String pattern)
375 376 377
  {
    this (pattern, new DecimalFormatSymbols ());
  }
Tom Tromey committed
378 379

  public DecimalFormat (String pattern, DecimalFormatSymbols symbols)
380 381 382 383
  {
    this.symbols = symbols;
    applyPattern (pattern);
  }
Tom Tromey committed
384 385

  private final boolean equals (String s1, String s2)
386 387 388 389 390
  {
    if (s1 == null || s2 == null)
      return s1 == s2;
    return s1.equals(s2);
  }
Tom Tromey committed
391 392

  public boolean equals (Object obj)
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
  {
    if (! (obj instanceof DecimalFormat))
      return false;
    DecimalFormat dup = (DecimalFormat) obj;
    return (decimalSeparatorAlwaysShown == dup.decimalSeparatorAlwaysShown
	    && groupingSize == dup.groupingSize
	    && minExponentDigits == dup.minExponentDigits
	    && multiplier == dup.multiplier
	    && equals(negativePrefix, dup.negativePrefix)
	    && equals(negativeSuffix, dup.negativeSuffix)
	    && equals(positivePrefix, dup.positivePrefix)
	    && equals(positiveSuffix, dup.positiveSuffix)
	    && symbols.equals(dup.symbols)
	    && useExponentialNotation == dup.useExponentialNotation);
  }
Tom Tromey committed
408 409 410

  public StringBuffer format (double number, StringBuffer dest,
			      FieldPosition fieldPos)
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
  {
    // A very special case.
    if (Double.isNaN(number))
      {
	dest.append(symbols.getNaN());
	if (fieldPos != null && fieldPos.getField() == INTEGER_FIELD)
	  {
	    int index = dest.length();
	    fieldPos.setBeginIndex(index - symbols.getNaN().length());
	    fieldPos.setEndIndex(index);
	  }
	return dest;
      }

    boolean is_neg = number < 0;
    if (is_neg)
      {
	if (negativePrefix != null)
	  dest.append(negativePrefix);
	else
	  {
	    dest.append(symbols.getMinusSign());
	    dest.append(positivePrefix);
	  }
	number = - number;
      }
    else
      dest.append(positivePrefix);

    int integerBeginIndex = dest.length();
    int integerEndIndex = 0;
    if (Double.isInfinite (number))
      {
	dest.append(symbols.getInfinity());
	integerEndIndex = dest.length();
      }
    else
      {
	number *= multiplier;

	// Compute exponent.
	long exponent = 0;
	double baseNumber;
	if (useExponentialNotation)
	  {
456
	    exponent = (long) Math.floor (Math.log(number) / Math.log(10));
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
	    if (minimumIntegerDigits > 0)
	      exponent -= minimumIntegerDigits - 1;
	    baseNumber = (long) (number / Math.pow(10.0, exponent));
	  }
	else
	  baseNumber = number;

	// Round to the correct number of digits.
	baseNumber += 5 * Math.pow(10.0, - maximumFractionDigits - 1);

	int index = dest.length();
	double intPart = Math.floor(baseNumber);
	int count = 0;
	while (count < maximumIntegerDigits
	       && (intPart > 0 || count < minimumIntegerDigits))
	  {
	    long dig = (long) (intPart % 10);
	    intPart = Math.floor(intPart / 10);

	    // Append group separator if required.
	    if (groupingUsed && count > 0 && count % groupingSize == 0)
	      dest.insert(index, symbols.getGroupingSeparator());

	    dest.insert(index, (char) (symbols.getZeroDigit() + dig));

	    ++count;
	  }

	integerEndIndex = dest.length();

	int decimal_index = integerEndIndex;
	int consecutive_zeros = 0;
	int total_digits = 0;

	// Strip integer part from NUMBER.
	double fracPart = baseNumber - Math.floor(baseNumber);
	for (count = 0;
	     count < maximumFractionDigits
	       && (fracPart != 0 || count < minimumFractionDigits);
	     ++count)
	  {
	    ++total_digits;
	    fracPart *= 10;
	    long dig = (long) fracPart;
	    if (dig == 0)
	      ++consecutive_zeros;
	    else
	      consecutive_zeros = 0;
	    dest.append((char) (symbols.getZeroDigit() + dig));

	    // Strip integer part from FRACPART.
	    fracPart = fracPart - Math.floor (fracPart);
	  }

	// Strip extraneous trailing `0's.  We can't always detect
	// these in the loop.
	int extra_zeros = Math.min (consecutive_zeros,
				    total_digits - minimumFractionDigits);
	if (extra_zeros > 0)
	  {
	    dest.setLength(dest.length() - extra_zeros);
	    total_digits -= extra_zeros;
	  }

	// If required, add the decimal symbol.
	if (decimalSeparatorAlwaysShown
	    || total_digits > 0)
	  {
	    dest.insert(decimal_index, symbols.getDecimalSeparator());
	    if (fieldPos != null && fieldPos.getField() == FRACTION_FIELD)
	      {
		fieldPos.setBeginIndex(decimal_index + 1);
		fieldPos.setEndIndex(dest.length());
	      }
	  }

	// Finally, print the exponent.
	if (useExponentialNotation)
	  {
	    dest.append(symbols.getExponential());
537 538 539 540 541
	    if (exponent < 0)
	      {
		dest.append (symbols.getMinusSign ());
		exponent = - exponent;
	      }
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
	    index = dest.length();
	    for (count = 0;
		 exponent > 0 || count < minExponentDigits;
		 ++count)
	      {
		long dig = exponent % 10;
		exponent /= 10;
		dest.insert(index, (char) (symbols.getZeroDigit() + dig));
	      }
	  }
      }

    if (fieldPos != null && fieldPos.getField() == INTEGER_FIELD)
      {
	fieldPos.setBeginIndex(integerBeginIndex);
	fieldPos.setEndIndex(integerEndIndex);
      }

    dest.append((is_neg && negativeSuffix != null)
		? negativeSuffix
		: positiveSuffix);
    return dest;
  }
Tom Tromey committed
565 566 567

  public StringBuffer format (long number, StringBuffer dest,
			      FieldPosition fieldPos)
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 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 631 632 633 634 635 636
  {
    // If using exponential notation, we just format as a double.
    if (useExponentialNotation)
      return format ((double) number, dest, fieldPos);

    boolean is_neg = number < 0;
    if (is_neg)
      {
	if (negativePrefix != null)
	  dest.append(negativePrefix);
	else
	  {
	    dest.append(symbols.getMinusSign());
	    dest.append(positivePrefix);
	  }
	number = - number;
      }
    else
      dest.append(positivePrefix);

    int integerBeginIndex = dest.length();
    int index = dest.length();
    int count = 0;
    while (count < maximumIntegerDigits
	   && (number > 0 || count < minimumIntegerDigits))
      {
	long dig = number % 10;
	number /= 10;
	// NUMBER and DIG will be less than 0 if the original number
	// was the most negative long.
	if (dig < 0)
	  {
	    dig = - dig;
	    number = - number;
	  }

	// Append group separator if required.
	if (groupingUsed && count > 0 && count % groupingSize == 0)
	  dest.insert(index, symbols.getGroupingSeparator());

	dest.insert(index, (char) (symbols.getZeroDigit() + dig));

	++count;
      }

    if (fieldPos != null && fieldPos.getField() == INTEGER_FIELD)
      {
	fieldPos.setBeginIndex(integerBeginIndex);
	fieldPos.setEndIndex(dest.length());
      }

    if (decimalSeparatorAlwaysShown || minimumFractionDigits > 0)
      {
	dest.append(symbols.getDecimalSeparator());
	if (fieldPos != null && fieldPos.getField() == FRACTION_FIELD)
	  {
	    fieldPos.setBeginIndex(dest.length());
	    fieldPos.setEndIndex(dest.length() + minimumFractionDigits);
	  }
      }

    for (count = 0; count < minimumFractionDigits; ++count)
      dest.append(symbols.getZeroDigit());

    dest.append((is_neg && negativeSuffix != null)
		? negativeSuffix
		: positiveSuffix);
    return dest;
  }
Tom Tromey committed
637 638

  public DecimalFormatSymbols getDecimalFormatSymbols ()
639 640 641
  {
    return symbols;
  }
Tom Tromey committed
642 643

  public int getGroupingSize ()
644 645 646
  {
    return groupingSize;
  }
Tom Tromey committed
647 648

  public int getMultiplier ()
649 650 651
  {
    return multiplier;
  }
Tom Tromey committed
652 653

  public String getNegativePrefix ()
654 655 656
  {
    return negativePrefix;
  }
Tom Tromey committed
657 658

  public String getNegativeSuffix ()
659 660 661
  {
    return negativeSuffix;
  }
Tom Tromey committed
662 663

  public String getPositivePrefix ()
664 665 666
  {
    return positivePrefix;
  }
Tom Tromey committed
667 668

  public String getPositiveSuffix ()
669 670 671
  {
    return positiveSuffix;
  }
Tom Tromey committed
672 673

  public int hashCode ()
674 675 676 677 678 679
  {
    int hash = (negativeSuffix.hashCode() ^ negativePrefix.hashCode()
		^positivePrefix.hashCode() ^ positiveSuffix.hashCode());
    // FIXME.
    return hash;
  }
Tom Tromey committed
680 681

  public boolean isDecimalSeparatorAlwaysShown ()
682 683 684
  {
    return decimalSeparatorAlwaysShown;
  }
Tom Tromey committed
685 686

  public Number parse (String str, ParsePosition pos)
687 688 689 690
  {
    // Our strategy is simple: copy the text into a buffer,
    // translating or omitting locale-specific information.  Then
    // let Double or Long convert the number for us.
Tom Tromey committed
691

692 693 694
    boolean is_neg = false;
    int index = pos.getIndex();
    StringBuffer buf = new StringBuffer ();
Tom Tromey committed
695

Tom Tromey committed
696 697
    // We have to check both prefixes, because one might be empty.  We
    // want to pick the longest prefix that matches.
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    boolean got_pos = str.startsWith(positivePrefix, index);
    String np = (negativePrefix != null
		 ? negativePrefix
		 : positivePrefix + symbols.getMinusSign());
    boolean got_neg = str.startsWith(np, index);

    if (got_pos && got_neg)
      {
	// By checking this way, we preserve ambiguity in the case
	// where the negative format differs only in suffix.  We
	// check this again later.
	if (np.length() > positivePrefix.length())
	  {
	    is_neg = true;
	    index += np.length();
	  }
	else
	  index += positivePrefix.length();
      }
    else if (got_neg)
      {
	is_neg = true;
	index += np.length();
      }
    else if (got_pos)
      index += positivePrefix.length();
    else
      {
	pos.setErrorIndex (index);
	return null;
      }

    // FIXME: handle Inf and NaN.
Tom Tromey committed
731

Tom Tromey committed
732 733
    // FIXME: do we have to respect minimum digits?
    // What about leading zeros?  What about multiplier?
Tom Tromey committed
734

735 736
    int start_index = index;
    int max = str.length();
Tom Tromey committed
737 738 739
    int last = index + maximumIntegerDigits;
    if (last > 0 && max > last)
      max = last;
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
    char zero = symbols.getZeroDigit();
    int last_group = -1;
    boolean int_part = true;
    boolean exp_part = false;
    for (; index < max; ++index)
      {
	char c = str.charAt(index);

	// FIXME: what about grouping size?
	if (groupingUsed && c == symbols.getGroupingSeparator())
	  {
	    if (last_group != -1
		&& (index - last_group) % groupingSize != 0)
	      {
		pos.setErrorIndex(index);
		return null;
	      }
	    last_group = index;
	  }
	else if (c >= zero && c <= zero + 9)
	  {
	    buf.append((char) (c - zero + '0'));
	    exp_part = false;
	  }
	else if (parseIntegerOnly)
	  break;
	else if (c == symbols.getDecimalSeparator())
	  {
	    if (last_group != -1
		&& (index - last_group) % groupingSize != 0)
	      {
		pos.setErrorIndex(index);
		return null;
	      }
	    buf.append('.');
	    int_part = false;
	  }
	else if (c == symbols.getExponential())
	  {
	    buf.append('E');
	    int_part = false;
	    exp_part = true;
	  }
	else if (exp_part
		 && (c == '+' || c == '-' || c == symbols.getMinusSign()))
	  {
	    // For exponential notation.
	    buf.append(c);
	  }
	else
	  break;
      }

    if (index == start_index)
      {
	// Didn't see any digits.
	pos.setErrorIndex(index);
	return null;
      }

    // Check the suffix.  We must do this before converting the
    // buffer to a number to handle the case of a number which is
    // the most negative Long.
    boolean got_pos_suf = str.startsWith(positiveSuffix, index);
    String ns = (negativePrefix == null ? positiveSuffix : negativeSuffix);
    boolean got_neg_suf = str.startsWith(ns, index);
    if (is_neg)
      {
	if (! got_neg_suf)
	  {
	    pos.setErrorIndex(index);
	    return null;
	  }
      }
    else if (got_pos && got_neg && got_neg_suf)
      {
	is_neg = true;
      }
    else if (got_pos != got_pos_suf && got_neg != got_neg_suf)
      {
	pos.setErrorIndex(index);
	return null;
      }

    String suffix = is_neg ? ns : positiveSuffix;
    if (is_neg)
      buf.insert(0, '-');

    String t = buf.toString();
    Number result = null;
    try
      {
	result = new Long (t);
      }
    catch (NumberFormatException x1)
      {
	try
	  {
	    result = new Double (t);
	  }
	catch (NumberFormatException x2)
	  {
	  }
      }
    if (result == null)
      {
	pos.setErrorIndex(index);
	return null;
      }

    pos.setIndex(index + suffix.length());

    return result;
  }
Tom Tromey committed
854 855

  public void setDecimalFormatSymbols (DecimalFormatSymbols newSymbols)
856 857 858
  {
    symbols = newSymbols;
  }
Tom Tromey committed
859 860

  public void setDecimalSeparatorAlwaysShown (boolean newValue)
861 862 863
  {
    decimalSeparatorAlwaysShown = newValue;
  }
Tom Tromey committed
864 865

  public void setGroupingSize (int groupSize)
866 867 868
  {
    groupingSize = (byte) groupSize;
  }
Tom Tromey committed
869 870

  public void setMaximumFractionDigits (int newValue)
871 872 873
  {
    maximumFractionDigits = Math.min(newValue, 340);
  }
Tom Tromey committed
874 875

  public void setMaximumIntegerDigits (int newValue)
876 877 878
  {
    maximumIntegerDigits = Math.min(newValue, 309);
  }
Tom Tromey committed
879 880

  public void setMinimumFractionDigits (int newValue)
881 882 883
  {
    minimumFractionDigits = Math.min(newValue, 340);
  }
Tom Tromey committed
884 885

  public void setMinimumIntegerDigits (int newValue)
886 887 888
  {
    minimumIntegerDigits = Math.min(newValue, 309);
  }
Tom Tromey committed
889 890

  public void setMultiplier (int newValue)
891 892 893
  {
    multiplier = newValue;
  }
Tom Tromey committed
894 895

  public void setNegativePrefix (String newValue)
896 897 898
  {
    negativePrefix = newValue;
  }
Tom Tromey committed
899 900

  public void setNegativeSuffix (String newValue)
901 902 903
  {
    negativeSuffix = newValue;
  }
Tom Tromey committed
904 905

  public void setPositivePrefix (String newValue)
906 907 908
  {
    positivePrefix = newValue;
  }
Tom Tromey committed
909 910

  public void setPositiveSuffix (String newValue)
911 912 913
  {
    positiveSuffix = newValue;
  }
Tom Tromey committed
914 915

  private final void quoteFix (StringBuffer buf, String text, String patChars)
916 917 918 919 920 921 922 923
  {
    int len = text.length();
    for (int index = 0; index < len; ++index)
      {
	char c = text.charAt(index);
	if (patChars.indexOf(c) != -1)
	  {
	    buf.append('\'');
Tom Tromey committed
924
	    buf.append(c);
925 926 927 928 929 930
	    buf.append('\'');
	  }
	else
	  buf.append(c);
      }
  }
Tom Tromey committed
931 932

  private final String computePattern (DecimalFormatSymbols syms)
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 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
  {
    StringBuffer mainPattern = new StringBuffer ();
    // We have to at least emit a zero for the minimum number of
    // digits.  Past that we need hash marks up to the grouping
    // separator (and one beyond).
    int total_digits = Math.max(minimumIntegerDigits,
				groupingUsed ? groupingSize + 1: 0);
    for (int i = 0; i < total_digits - minimumIntegerDigits; ++i)
      mainPattern.append(syms.getDigit());
    for (int i = total_digits - minimumIntegerDigits; i < total_digits; ++i)
      mainPattern.append(syms.getZeroDigit());
    // Inserting the gropuing operator afterwards is easier.
    if (groupingUsed)
      mainPattern.insert(mainPattern.length() - groupingSize,
			 syms.getGroupingSeparator());
    // See if we need decimal info.
    if (minimumFractionDigits > 0 || maximumFractionDigits > 0
	|| decimalSeparatorAlwaysShown)
      mainPattern.append(syms.getDecimalSeparator());
    for (int i = 0; i < minimumFractionDigits; ++i)
      mainPattern.append(syms.getZeroDigit());
    for (int i = minimumFractionDigits; i < maximumFractionDigits; ++i)
      mainPattern.append(syms.getDigit());
    if (useExponentialNotation)
      {
	mainPattern.append(syms.getExponential());
	for (int i = 0; i < minExponentDigits; ++i)
	  mainPattern.append(syms.getZeroDigit());
	if (minExponentDigits == 0)
	  mainPattern.append(syms.getDigit());
      }

    String main = mainPattern.toString();
    String patChars = patternChars (syms);
    mainPattern.setLength(0);

    quoteFix (mainPattern, positivePrefix, patChars);
    mainPattern.append(main);
    quoteFix (mainPattern, positiveSuffix, patChars);

    if (negativePrefix != null)
      {
	quoteFix (mainPattern, negativePrefix, patChars);
	mainPattern.append(main);
	quoteFix (mainPattern, negativeSuffix, patChars);
      }

    return mainPattern.toString();
  }
Tom Tromey committed
982 983

  public String toLocalizedPattern ()
984 985 986
  {
    return computePattern (symbols);
  }
Tom Tromey committed
987 988

  public String toPattern ()
989 990 991
  {
    return computePattern (nonLocalizedSymbols);
  }
Tom Tromey committed
992 993 994 995 996 997 998 999 1000 1001

  // These names are fixed by the serialization spec.
  private boolean decimalSeparatorAlwaysShown;
  private byte groupingSize;
  private byte minExponentDigits;
  private int multiplier;
  private String negativePrefix;
  private String negativeSuffix;
  private String positivePrefix;
  private String positiveSuffix;
1002
  private int serialVersionOnStream = 1;
Tom Tromey committed
1003 1004
  private DecimalFormatSymbols symbols;
  private boolean useExponentialNotation;
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
  private static final long serialVersionUID = 864413376551465018L;

  private void readObject(ObjectInputStream stream)
    throws IOException, ClassNotFoundException
  {
    stream.defaultReadObject();
    if (serialVersionOnStream < 1)
      {
        useExponentialNotation = false;
	serialVersionOnStream = 1;
      }
  }
Tom Tromey committed
1017 1018 1019 1020 1021 1022

  // The locale-independent pattern symbols happen to be the same as
  // the US symbols.
  private static final DecimalFormatSymbols nonLocalizedSymbols
    = new DecimalFormatSymbols (Locale.US);
}