408 String[] all = adapter.getLocaleResources(def).getNumberPatterns();
409
410 // Always applyPattern after the symbols are set
411 this.symbols = DecimalFormatSymbols.getInstance(def);
412 applyPattern(all[0], false);
413 }
414
415
416 /**
417 * Creates a DecimalFormat using the given pattern and the symbols
418 * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
419 * This is a convenient way to obtain a
420 * DecimalFormat when internationalization is not the main concern.
421 * <p>
422 * To obtain standard formats for a given locale, use the factory methods
423 * on NumberFormat such as getNumberInstance. These factories will
424 * return the most appropriate sub-class of NumberFormat for a given
425 * locale.
426 *
427 * @param pattern a non-localized pattern string.
428 * @exception NullPointerException if {@code pattern} is null
429 * @exception IllegalArgumentException if the given pattern is invalid.
430 * @see java.text.NumberFormat#getInstance
431 * @see java.text.NumberFormat#getNumberInstance
432 * @see java.text.NumberFormat#getCurrencyInstance
433 * @see java.text.NumberFormat#getPercentInstance
434 */
435 public DecimalFormat(String pattern) {
436 // Always applyPattern after the symbols are set
437 this.symbols = DecimalFormatSymbols.getInstance(Locale.getDefault(Locale.Category.FORMAT));
438 applyPattern(pattern, false);
439 }
440
441
442 /**
443 * Creates a DecimalFormat using the given pattern and symbols.
444 * Use this constructor when you need to completely customize the
445 * behavior of the format.
446 * <p>
447 * To obtain standard formats for a given
448 * locale, use the factory methods on NumberFormat such as
449 * getInstance or getCurrencyInstance. If you need only minor adjustments
450 * to a standard format, you can modify the format returned by
451 * a NumberFormat factory method.
452 *
453 * @param pattern a non-localized pattern string
454 * @param symbols the set of symbols to be used
455 * @exception NullPointerException if any of the given arguments is null
456 * @exception IllegalArgumentException if the given pattern is invalid
457 * @see java.text.NumberFormat#getInstance
458 * @see java.text.NumberFormat#getNumberInstance
459 * @see java.text.NumberFormat#getCurrencyInstance
460 * @see java.text.NumberFormat#getPercentInstance
461 * @see java.text.DecimalFormatSymbols
462 */
463 public DecimalFormat (String pattern, DecimalFormatSymbols symbols) {
464 // Always applyPattern after the symbols are set
465 this.symbols = (DecimalFormatSymbols)symbols.clone();
466 applyPattern(pattern, false);
467 }
468
469
470 // Overrides
471 /**
472 * Formats a number and appends the resulting text to the given string
473 * buffer.
474 * The number can be of any subclass of {@link java.lang.Number}.
475 * <p>
476 * This implementation uses the maximum precision permitted.
477 * @param number the number to format
478 * @param toAppendTo the {@code StringBuffer} to which the formatted
479 * text is to be appended
480 * @param pos keeps track on the position of the field within the
481 * returned string. For example, for formatting a number
482 * {@code 1234567.89} in {@code Locale.US} locale,
483 * if the given {@code fieldPosition} is
484 * {@link NumberFormat#INTEGER_FIELD}, the begin index
485 * and end index of {@code fieldPosition} will be set
486 * to 0 and 9, respectively for the output string
487 * {@code 1,234,567.89}.
488 * @return the value passed in as {@code toAppendTo}
489 * @exception IllegalArgumentException if {@code number} is
490 * null or not an instance of {@code Number}.
491 * @exception NullPointerException if {@code toAppendTo} or
492 * {@code pos} is null
493 * @exception ArithmeticException if rounding is needed with rounding
494 * mode being set to RoundingMode.UNNECESSARY
495 * @see java.text.FieldPosition
496 */
497 @Override
498 public final StringBuffer format(Object number,
499 StringBuffer toAppendTo,
500 FieldPosition pos) {
501 if (number instanceof Long || number instanceof Integer ||
502 number instanceof Short || number instanceof Byte ||
503 number instanceof AtomicInteger ||
504 number instanceof AtomicLong ||
505 (number instanceof BigInteger &&
506 ((BigInteger)number).bitLength () < 64)) {
507 return format(((Number)number).longValue(), toAppendTo, pos);
508 } else if (number instanceof BigDecimal) {
509 return format((BigDecimal)number, toAppendTo, pos);
510 } else if (number instanceof BigInteger) {
511 return format((BigInteger)number, toAppendTo, pos);
512 } else if (number instanceof Number) {
513 return format(((Number)number).doubleValue(), toAppendTo, pos);
514 } else {
515 throw new IllegalArgumentException("Cannot format given Object as a Number");
516 }
517 }
518
519 /**
520 * Formats a double to produce a string.
521 * @param number The double to format
522 * @param result where the text is to be appended
523 * @param fieldPosition keeps track on the position of the field within
524 * the returned string. For example, for formatting
525 * a number {@code 1234567.89} in {@code Locale.US}
526 * locale, if the given {@code fieldPosition} is
527 * {@link NumberFormat#INTEGER_FIELD}, the begin index
528 * and end index of {@code fieldPosition} will be set
529 * to 0 and 9, respectively for the output string
530 * {@code 1,234,567.89}.
531 * @exception NullPointerException if {@code result} or
532 * {@code fieldPosition} is {@code null}
533 * @exception ArithmeticException if rounding is needed with rounding
534 * mode being set to RoundingMode.UNNECESSARY
535 * @return The formatted number string
536 * @see java.text.FieldPosition
537 */
538 @Override
539 public StringBuffer format(double number, StringBuffer result,
540 FieldPosition fieldPosition) {
541 // If fieldPosition is a DontCareFieldPosition instance we can
542 // try to go to fast-path code.
543 boolean tryFastPath = false;
544 if (fieldPosition == DontCareFieldPosition.INSTANCE)
545 tryFastPath = true;
546 else {
547 fieldPosition.setBeginIndex(0);
548 fieldPosition.setEndIndex(0);
549 }
550
551 if (tryFastPath) {
552 String tempResult = fastFormat(number);
553 if (tempResult != null) {
554 result.append(tempResult);
555 return result;
556 }
557 }
558
559 // if fast-path could not work, we fallback to standard code.
560 return format(number, result, fieldPosition.getFieldDelegate());
561 }
562
563 /**
564 * Formats a double to produce a string.
565 * @param number The double to format
566 * @param result where the text is to be appended
567 * @param delegate notified of locations of sub fields
568 * @exception ArithmeticException if rounding is needed with rounding
569 * mode being set to RoundingMode.UNNECESSARY
570 * @return The formatted number string
571 */
572 StringBuffer format(double number, StringBuffer result,
573 FieldDelegate delegate) {
574
575 boolean nanOrInfinity = handleNaN(number, result, delegate);
576 if (nanOrInfinity) {
577 return result;
578 }
579
580 /* Detecting whether a double is negative is easy with the exception of
581 * the value -0.0. This is a double which has a zero mantissa (and
582 * exponent), but a negative sign bit. It is semantically distinct from
583 * a zero with a positive sign bit, and this distinction is important
584 * to certain kinds of computations. However, it's a little tricky to
585 * detect, since (-0.0 == 0.0) and !(-0.0 < 0.0). How then, you may
586 * ask, does it behave distinctly from +0.0? Well, 1/(-0.0) ==
587 * -Infinity. Proper detection of -0.0 is needed to deal with the
588 * issues raised by bugs 4106658, 4106667, and 4147706. Liu 7/6/98.
681 digitList.set(isNegative, number, useExponentialNotation
682 ? maxIntDigits + maxFraDigits : maxFraDigits,
683 !useExponentialNotation);
684 return subformat(result, delegate, isNegative, false,
685 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
686 }
687 }
688
689 /**
690 * Format a long to produce a string.
691 * @param number The long to format
692 * @param result where the text is to be appended
693 * @param fieldPosition keeps track on the position of the field within
694 * the returned string. For example, for formatting
695 * a number {@code 123456789} in {@code Locale.US}
696 * locale, if the given {@code fieldPosition} is
697 * {@link NumberFormat#INTEGER_FIELD}, the begin index
698 * and end index of {@code fieldPosition} will be set
699 * to 0 and 11, respectively for the output string
700 * {@code 123,456,789}.
701 * @exception NullPointerException if {@code result} or
702 * {@code fieldPosition} is {@code null}
703 * @exception ArithmeticException if rounding is needed with rounding
704 * mode being set to RoundingMode.UNNECESSARY
705 * @return The formatted number string
706 * @see java.text.FieldPosition
707 */
708 @Override
709 public StringBuffer format(long number, StringBuffer result,
710 FieldPosition fieldPosition) {
711 fieldPosition.setBeginIndex(0);
712 fieldPosition.setEndIndex(0);
713
714 return format(number, result, fieldPosition.getFieldDelegate());
715 }
716
717 /**
718 * Format a long to produce a string.
719 * @param number The long to format
720 * @param result where the text is to be appended
721 * @param delegate notified of locations of sub fields
722 * @return The formatted number string
723 * @exception ArithmeticException if rounding is needed with rounding
724 * mode being set to RoundingMode.UNNECESSARY
725 * @see java.text.FieldPosition
726 */
727 StringBuffer format(long number, StringBuffer result,
728 FieldDelegate delegate) {
729 boolean isNegative = (number < 0);
730 if (isNegative) {
731 number = -number;
732 }
733
734 // In general, long values always represent real finite numbers, so
735 // we don't have to check for +/- Infinity or NaN. However, there
736 // is one case we have to be careful of: The multiplier can push
737 // a number near MIN_VALUE or MAX_VALUE outside the legal range. We
738 // check for this before multiplying, and if it happens we use
739 // BigInteger instead.
740 boolean useBigInteger = false;
741 if (number < 0) { // This can only happen if number == Long.MIN_VALUE.
742 if (multiplier != 0) {
743 useBigInteger = true;
778 useExponentialNotation ? maxIntDigits + maxFraDigits : 0);
779
780 return subformat(result, delegate, isNegative, true,
781 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
782 }
783 }
784
785 /**
786 * Formats a BigDecimal to produce a string.
787 * @param number The BigDecimal to format
788 * @param result where the text is to be appended
789 * @param fieldPosition keeps track on the position of the field within
790 * the returned string. For example, for formatting
791 * a number {@code 1234567.89} in {@code Locale.US}
792 * locale, if the given {@code fieldPosition} is
793 * {@link NumberFormat#INTEGER_FIELD}, the begin index
794 * and end index of {@code fieldPosition} will be set
795 * to 0 and 9, respectively for the output string
796 * {@code 1,234,567.89}.
797 * @return The formatted number string
798 * @exception ArithmeticException if rounding is needed with rounding
799 * mode being set to RoundingMode.UNNECESSARY
800 * @see java.text.FieldPosition
801 */
802 private StringBuffer format(BigDecimal number, StringBuffer result,
803 FieldPosition fieldPosition) {
804 fieldPosition.setBeginIndex(0);
805 fieldPosition.setEndIndex(0);
806 return format(number, result, fieldPosition.getFieldDelegate());
807 }
808
809 /**
810 * Formats a BigDecimal to produce a string.
811 * @param number The BigDecimal to format
812 * @param result where the text is to be appended
813 * @param delegate notified of locations of sub fields
814 * @exception ArithmeticException if rounding is needed with rounding
815 * mode being set to RoundingMode.UNNECESSARY
816 * @return The formatted number string
817 */
818 StringBuffer format(BigDecimal number, StringBuffer result,
819 FieldDelegate delegate) {
820 if (multiplier != 1) {
821 number = number.multiply(getBigDecimalMultiplier());
822 }
823 boolean isNegative = number.signum() == -1;
824 if (isNegative) {
825 number = number.negate();
826 }
827
828 synchronized(digitList) {
829 int maxIntDigits = getMaximumIntegerDigits();
830 int minIntDigits = getMinimumIntegerDigits();
831 int maxFraDigits = getMaximumFractionDigits();
832 int minFraDigits = getMinimumFractionDigits();
833 int maximumDigits = maxIntDigits + maxFraDigits;
834
837 maxFraDigits, !useExponentialNotation);
838
839 return subformat(result, delegate, isNegative, false,
840 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
841 }
842 }
843
844 /**
845 * Format a BigInteger to produce a string.
846 * @param number The BigInteger to format
847 * @param result where the text is to be appended
848 * @param fieldPosition keeps track on the position of the field within
849 * the returned string. For example, for formatting
850 * a number {@code 123456789} in {@code Locale.US}
851 * locale, if the given {@code fieldPosition} is
852 * {@link NumberFormat#INTEGER_FIELD}, the begin index
853 * and end index of {@code fieldPosition} will be set
854 * to 0 and 11, respectively for the output string
855 * {@code 123,456,789}.
856 * @return The formatted number string
857 * @exception ArithmeticException if rounding is needed with rounding
858 * mode being set to RoundingMode.UNNECESSARY
859 * @see java.text.FieldPosition
860 */
861 private StringBuffer format(BigInteger number, StringBuffer result,
862 FieldPosition fieldPosition) {
863 fieldPosition.setBeginIndex(0);
864 fieldPosition.setEndIndex(0);
865
866 return format(number, result, fieldPosition.getFieldDelegate(), false);
867 }
868
869 /**
870 * Format a BigInteger to produce a string.
871 * @param number The BigInteger to format
872 * @param result where the text is to be appended
873 * @param delegate notified of locations of sub fields
874 * @return The formatted number string
875 * @exception ArithmeticException if rounding is needed with rounding
876 * mode being set to RoundingMode.UNNECESSARY
877 * @see java.text.FieldPosition
878 */
879 StringBuffer format(BigInteger number, StringBuffer result,
880 FieldDelegate delegate, boolean formatLong) {
881 if (multiplier != 1) {
882 number = number.multiply(getBigIntegerMultiplier());
883 }
884 boolean isNegative = number.signum() == -1;
885 if (isNegative) {
886 number = number.negate();
887 }
888
889 synchronized(digitList) {
890 int maxIntDigits, minIntDigits, maxFraDigits, minFraDigits, maximumDigits;
891 if (formatLong) {
892 maxIntDigits = super.getMaximumIntegerDigits();
893 minIntDigits = super.getMinimumIntegerDigits();
894 maxFraDigits = super.getMaximumFractionDigits();
895 minFraDigits = super.getMinimumFractionDigits();
906 }
907
908 digitList.set(isNegative, number,
909 useExponentialNotation ? maximumDigits : 0);
910
911 return subformat(result, delegate, isNegative, true,
912 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
913 }
914 }
915
916 /**
917 * Formats an Object producing an {@code AttributedCharacterIterator}.
918 * You can use the returned {@code AttributedCharacterIterator}
919 * to build the resulting String, as well as to determine information
920 * about the resulting String.
921 * <p>
922 * Each attribute key of the AttributedCharacterIterator will be of type
923 * {@code NumberFormat.Field}, with the attribute value being the
924 * same as the attribute key.
925 *
926 * @exception NullPointerException if obj is null.
927 * @exception IllegalArgumentException when the Format cannot format the
928 * given object.
929 * @exception ArithmeticException if rounding is needed with rounding
930 * mode being set to RoundingMode.UNNECESSARY
931 * @param obj The object to format
932 * @return AttributedCharacterIterator describing the formatted value.
933 * @since 1.4
934 */
935 @Override
936 public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
937 CharacterIteratorFieldDelegate delegate =
938 new CharacterIteratorFieldDelegate();
939 StringBuffer sb = new StringBuffer();
940
941 if (obj instanceof Double || obj instanceof Float) {
942 format(((Number)obj).doubleValue(), sb, delegate);
943 } else if (obj instanceof Long || obj instanceof Integer ||
944 obj instanceof Short || obj instanceof Byte ||
945 obj instanceof AtomicInteger || obj instanceof AtomicLong) {
946 format(((Number)obj).longValue(), sb, delegate);
947 } else if (obj instanceof BigDecimal) {
948 format((BigDecimal)obj, sb, delegate);
949 } else if (obj instanceof BigInteger) {
2113 * the type they want.
2114 * <li>If {@code isParseBigDecimal()} is true, values are returned
2115 * as {@code BigDecimal} objects. The values are the ones
2116 * constructed by {@link java.math.BigDecimal#BigDecimal(String)}
2117 * for corresponding strings in locale-independent format. The
2118 * special cases negative and positive infinity and NaN are returned
2119 * as {@code Double} instances holding the values of the
2120 * corresponding {@code Double} constants.
2121 * </ul>
2122 * <p>
2123 * {@code DecimalFormat} parses all Unicode characters that represent
2124 * decimal digits, as defined by {@code Character.digit()}. In
2125 * addition, {@code DecimalFormat} also recognizes as digits the ten
2126 * consecutive characters starting with the localized zero digit defined in
2127 * the {@code DecimalFormatSymbols} object.
2128 *
2129 * @param text the string to be parsed
2130 * @param pos A {@code ParsePosition} object with index and error
2131 * index information as described above.
2132 * @return the parsed value, or {@code null} if the parse fails
2133 * @exception NullPointerException if {@code text} or
2134 * {@code pos} is null.
2135 */
2136 @Override
2137 public Number parse(String text, ParsePosition pos) {
2138 // special case NaN
2139 if (text.regionMatches(pos.index, symbols.getNaN(), 0, symbols.getNaN().length())) {
2140 pos.index = pos.index + symbols.getNaN().length();
2141 return Double.valueOf(Double.NaN);
2142 }
2143
2144 boolean[] status = new boolean[STATUS_LENGTH];
2145 if (!subparse(text, pos, positivePrefix, negativePrefix, digitList, false, status)) {
2146 return null;
2147 }
2148
2149 // special case INFINITY
2150 if (status[STATUS_INFINITE]) {
2151 if (status[STATUS_POSITIVE] == (multiplier >= 0)) {
2152 return Double.valueOf(Double.POSITIVE_INFINITY);
2153 } else {
3237
3238 /**
3239 * Apply the given pattern to this Format object. A pattern is a
3240 * short-hand specification for the various formatting properties.
3241 * These properties can also be changed individually through the
3242 * various setter methods.
3243 * <p>
3244 * There is no limit to integer digits set
3245 * by this routine, since that is the typical end-user desire;
3246 * use setMaximumInteger if you want to set a real value.
3247 * For negative numbers, use a second pattern, separated by a semicolon
3248 * <P>Example {@code "#,#00.0#"} → 1,234.56
3249 * <P>This means a minimum of 2 integer digits, 1 fraction digit, and
3250 * a maximum of 2 fraction digits.
3251 * <p>Example: {@code "#,#00.0#;(#,#00.0#)"} for negatives in
3252 * parentheses.
3253 * <p>In negative patterns, the minimum and maximum counts are ignored;
3254 * these are presumed to be set in the positive pattern.
3255 *
3256 * @param pattern a new pattern
3257 * @exception NullPointerException if {@code pattern} is null
3258 * @exception IllegalArgumentException if the given pattern is invalid.
3259 */
3260 public void applyPattern(String pattern) {
3261 applyPattern(pattern, false);
3262 }
3263
3264 /**
3265 * Apply the given pattern to this Format object. The pattern
3266 * is assumed to be in a localized notation. A pattern is a
3267 * short-hand specification for the various formatting properties.
3268 * These properties can also be changed individually through the
3269 * various setter methods.
3270 * <p>
3271 * There is no limit to integer digits set
3272 * by this routine, since that is the typical end-user desire;
3273 * use setMaximumInteger if you want to set a real value.
3274 * For negative numbers, use a second pattern, separated by a semicolon
3275 * <P>Example {@code "#,#00.0#"} → 1,234.56
3276 * <P>This means a minimum of 2 integer digits, 1 fraction digit, and
3277 * a maximum of 2 fraction digits.
3278 * <p>Example: {@code "#,#00.0#;(#,#00.0#)"} for negatives in
3279 * parentheses.
3280 * <p>In negative patterns, the minimum and maximum counts are ignored;
3281 * these are presumed to be set in the positive pattern.
3282 *
3283 * @param pattern a new pattern
3284 * @exception NullPointerException if {@code pattern} is null
3285 * @exception IllegalArgumentException if the given pattern is invalid.
3286 */
3287 public void applyLocalizedPattern(String pattern) {
3288 applyPattern(pattern, true);
3289 }
3290
3291 /**
3292 * Does the real work of applying a pattern.
3293 */
3294 private void applyPattern(String pattern, boolean localized) {
3295 char zeroDigit = PATTERN_ZERO_DIGIT;
3296 char groupingSeparator = PATTERN_GROUPING_SEPARATOR;
3297 char decimalSeparator = PATTERN_DECIMAL_SEPARATOR;
3298 char percent = PATTERN_PERCENT;
3299 char perMill = PATTERN_PER_MILLE;
3300 char digit = PATTERN_DIGIT;
3301 char separator = PATTERN_SEPARATOR;
3302 String exponent = PATTERN_EXPONENT;
3303 char minus = PATTERN_MINUS;
3304 if (localized) {
3305 zeroDigit = symbols.getZeroDigit();
3765 * {@link DecimalFormatSymbols#getCurrency DecimalFormatSymbols.getCurrency}
3766 * on this number format's symbols.
3767 *
3768 * @return the currency used by this decimal format, or {@code null}
3769 * @since 1.4
3770 */
3771 @Override
3772 public Currency getCurrency() {
3773 return symbols.getCurrency();
3774 }
3775
3776 /**
3777 * Sets the currency used by this number format when formatting
3778 * currency values. This does not update the minimum or maximum
3779 * number of fraction digits used by the number format.
3780 * The currency is set by calling
3781 * {@link DecimalFormatSymbols#setCurrency DecimalFormatSymbols.setCurrency}
3782 * on this number format's symbols.
3783 *
3784 * @param currency the new currency to be used by this decimal format
3785 * @exception NullPointerException if {@code currency} is null
3786 * @since 1.4
3787 */
3788 @Override
3789 public void setCurrency(Currency currency) {
3790 if (currency != symbols.getCurrency()) {
3791 symbols.setCurrency(currency);
3792 if (isCurrencyFormat) {
3793 expandAffixes();
3794 }
3795 }
3796 fastPathCheckNeeded = true;
3797 }
3798
3799 /**
3800 * Gets the {@link java.math.RoundingMode} used in this DecimalFormat.
3801 *
3802 * @return The {@code RoundingMode} used for this DecimalFormat.
3803 * @see #setRoundingMode(RoundingMode)
3804 * @since 1.6
3805 */
3806 @Override
3807 public RoundingMode getRoundingMode() {
3808 return roundingMode;
3809 }
3810
3811 /**
3812 * Sets the {@link java.math.RoundingMode} used in this DecimalFormat.
3813 *
3814 * @param roundingMode The {@code RoundingMode} to be used
3815 * @see #getRoundingMode()
3816 * @exception NullPointerException if {@code roundingMode} is null.
3817 * @since 1.6
3818 */
3819 @Override
3820 public void setRoundingMode(RoundingMode roundingMode) {
3821 if (roundingMode == null) {
3822 throw new NullPointerException();
3823 }
3824
3825 this.roundingMode = roundingMode;
3826 digitList.setRoundingMode(roundingMode);
3827 fastPathCheckNeeded = true;
3828 }
3829
3830 /**
3831 * Reads the default serializable fields from the stream and performs
3832 * validations and adjustments for older serialized versions. The
3833 * validations and adjustments are:
3834 * <ol>
3835 * <li>
3836 * Verify that the superclass's digit count fields correctly reflect
|
408 String[] all = adapter.getLocaleResources(def).getNumberPatterns();
409
410 // Always applyPattern after the symbols are set
411 this.symbols = DecimalFormatSymbols.getInstance(def);
412 applyPattern(all[0], false);
413 }
414
415
416 /**
417 * Creates a DecimalFormat using the given pattern and the symbols
418 * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
419 * This is a convenient way to obtain a
420 * DecimalFormat when internationalization is not the main concern.
421 * <p>
422 * To obtain standard formats for a given locale, use the factory methods
423 * on NumberFormat such as getNumberInstance. These factories will
424 * return the most appropriate sub-class of NumberFormat for a given
425 * locale.
426 *
427 * @param pattern a non-localized pattern string.
428 * @throws NullPointerException if {@code pattern} is null
429 * @throws IllegalArgumentException if the given pattern is invalid.
430 * @see java.text.NumberFormat#getInstance
431 * @see java.text.NumberFormat#getNumberInstance
432 * @see java.text.NumberFormat#getCurrencyInstance
433 * @see java.text.NumberFormat#getPercentInstance
434 */
435 public DecimalFormat(String pattern) {
436 // Always applyPattern after the symbols are set
437 this.symbols = DecimalFormatSymbols.getInstance(Locale.getDefault(Locale.Category.FORMAT));
438 applyPattern(pattern, false);
439 }
440
441
442 /**
443 * Creates a DecimalFormat using the given pattern and symbols.
444 * Use this constructor when you need to completely customize the
445 * behavior of the format.
446 * <p>
447 * To obtain standard formats for a given
448 * locale, use the factory methods on NumberFormat such as
449 * getInstance or getCurrencyInstance. If you need only minor adjustments
450 * to a standard format, you can modify the format returned by
451 * a NumberFormat factory method.
452 *
453 * @param pattern a non-localized pattern string
454 * @param symbols the set of symbols to be used
455 * @throws NullPointerException if any of the given arguments is null
456 * @throws IllegalArgumentException if the given pattern is invalid
457 * @see java.text.NumberFormat#getInstance
458 * @see java.text.NumberFormat#getNumberInstance
459 * @see java.text.NumberFormat#getCurrencyInstance
460 * @see java.text.NumberFormat#getPercentInstance
461 * @see java.text.DecimalFormatSymbols
462 */
463 public DecimalFormat (String pattern, DecimalFormatSymbols symbols) {
464 // Always applyPattern after the symbols are set
465 this.symbols = (DecimalFormatSymbols)symbols.clone();
466 applyPattern(pattern, false);
467 }
468
469
470 // Overrides
471 /**
472 * Formats a number and appends the resulting text to the given string
473 * buffer.
474 * The number can be of any subclass of {@link java.lang.Number}.
475 * <p>
476 * This implementation uses the maximum precision permitted.
477 * @param number the number to format
478 * @param toAppendTo the {@code StringBuffer} to which the formatted
479 * text is to be appended
480 * @param pos keeps track on the position of the field within the
481 * returned string. For example, for formatting a number
482 * {@code 1234567.89} in {@code Locale.US} locale,
483 * if the given {@code fieldPosition} is
484 * {@link NumberFormat#INTEGER_FIELD}, the begin index
485 * and end index of {@code fieldPosition} will be set
486 * to 0 and 9, respectively for the output string
487 * {@code 1,234,567.89}.
488 * @return the value passed in as {@code toAppendTo}
489 * @throws IllegalArgumentException if {@code number} is
490 * null or not an instance of {@code Number}.
491 * @throws NullPointerException if {@code toAppendTo} or
492 * {@code pos} is null
493 * @throws ArithmeticException if rounding is needed with rounding
494 * mode being set to RoundingMode.UNNECESSARY
495 * @see java.text.FieldPosition
496 */
497 @Override
498 public final StringBuffer format(Object number,
499 StringBuffer toAppendTo,
500 FieldPosition pos) {
501 if (number instanceof Long || number instanceof Integer ||
502 number instanceof Short || number instanceof Byte ||
503 number instanceof AtomicInteger ||
504 number instanceof AtomicLong ||
505 (number instanceof BigInteger &&
506 ((BigInteger)number).bitLength () < 64)) {
507 return format(((Number)number).longValue(), toAppendTo, pos);
508 } else if (number instanceof BigDecimal) {
509 return format((BigDecimal)number, toAppendTo, pos);
510 } else if (number instanceof BigInteger) {
511 return format((BigInteger)number, toAppendTo, pos);
512 } else if (number instanceof Number) {
513 return format(((Number)number).doubleValue(), toAppendTo, pos);
514 } else {
515 throw new IllegalArgumentException("Cannot format given Object as a Number");
516 }
517 }
518
519 /**
520 * Formats a double to produce a string.
521 * @param number The double to format
522 * @param result where the text is to be appended
523 * @param fieldPosition keeps track on the position of the field within
524 * the returned string. For example, for formatting
525 * a number {@code 1234567.89} in {@code Locale.US}
526 * locale, if the given {@code fieldPosition} is
527 * {@link NumberFormat#INTEGER_FIELD}, the begin index
528 * and end index of {@code fieldPosition} will be set
529 * to 0 and 9, respectively for the output string
530 * {@code 1,234,567.89}.
531 * @throws NullPointerException if {@code result} or
532 * {@code fieldPosition} is {@code null}
533 * @throws ArithmeticException if rounding is needed with rounding
534 * mode being set to RoundingMode.UNNECESSARY
535 * @return The formatted number string
536 * @see java.text.FieldPosition
537 */
538 @Override
539 public StringBuffer format(double number, StringBuffer result,
540 FieldPosition fieldPosition) {
541 // If fieldPosition is a DontCareFieldPosition instance we can
542 // try to go to fast-path code.
543 boolean tryFastPath = false;
544 if (fieldPosition == DontCareFieldPosition.INSTANCE)
545 tryFastPath = true;
546 else {
547 fieldPosition.setBeginIndex(0);
548 fieldPosition.setEndIndex(0);
549 }
550
551 if (tryFastPath) {
552 String tempResult = fastFormat(number);
553 if (tempResult != null) {
554 result.append(tempResult);
555 return result;
556 }
557 }
558
559 // if fast-path could not work, we fallback to standard code.
560 return format(number, result, fieldPosition.getFieldDelegate());
561 }
562
563 /**
564 * Formats a double to produce a string.
565 * @param number The double to format
566 * @param result where the text is to be appended
567 * @param delegate notified of locations of sub fields
568 * @throws ArithmeticException if rounding is needed with rounding
569 * mode being set to RoundingMode.UNNECESSARY
570 * @return The formatted number string
571 */
572 StringBuffer format(double number, StringBuffer result,
573 FieldDelegate delegate) {
574
575 boolean nanOrInfinity = handleNaN(number, result, delegate);
576 if (nanOrInfinity) {
577 return result;
578 }
579
580 /* Detecting whether a double is negative is easy with the exception of
581 * the value -0.0. This is a double which has a zero mantissa (and
582 * exponent), but a negative sign bit. It is semantically distinct from
583 * a zero with a positive sign bit, and this distinction is important
584 * to certain kinds of computations. However, it's a little tricky to
585 * detect, since (-0.0 == 0.0) and !(-0.0 < 0.0). How then, you may
586 * ask, does it behave distinctly from +0.0? Well, 1/(-0.0) ==
587 * -Infinity. Proper detection of -0.0 is needed to deal with the
588 * issues raised by bugs 4106658, 4106667, and 4147706. Liu 7/6/98.
681 digitList.set(isNegative, number, useExponentialNotation
682 ? maxIntDigits + maxFraDigits : maxFraDigits,
683 !useExponentialNotation);
684 return subformat(result, delegate, isNegative, false,
685 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
686 }
687 }
688
689 /**
690 * Format a long to produce a string.
691 * @param number The long to format
692 * @param result where the text is to be appended
693 * @param fieldPosition keeps track on the position of the field within
694 * the returned string. For example, for formatting
695 * a number {@code 123456789} in {@code Locale.US}
696 * locale, if the given {@code fieldPosition} is
697 * {@link NumberFormat#INTEGER_FIELD}, the begin index
698 * and end index of {@code fieldPosition} will be set
699 * to 0 and 11, respectively for the output string
700 * {@code 123,456,789}.
701 * @throws NullPointerException if {@code result} or
702 * {@code fieldPosition} is {@code null}
703 * @throws ArithmeticException if rounding is needed with rounding
704 * mode being set to RoundingMode.UNNECESSARY
705 * @return The formatted number string
706 * @see java.text.FieldPosition
707 */
708 @Override
709 public StringBuffer format(long number, StringBuffer result,
710 FieldPosition fieldPosition) {
711 fieldPosition.setBeginIndex(0);
712 fieldPosition.setEndIndex(0);
713
714 return format(number, result, fieldPosition.getFieldDelegate());
715 }
716
717 /**
718 * Format a long to produce a string.
719 * @param number The long to format
720 * @param result where the text is to be appended
721 * @param delegate notified of locations of sub fields
722 * @return The formatted number string
723 * @throws ArithmeticException if rounding is needed with rounding
724 * mode being set to RoundingMode.UNNECESSARY
725 * @see java.text.FieldPosition
726 */
727 StringBuffer format(long number, StringBuffer result,
728 FieldDelegate delegate) {
729 boolean isNegative = (number < 0);
730 if (isNegative) {
731 number = -number;
732 }
733
734 // In general, long values always represent real finite numbers, so
735 // we don't have to check for +/- Infinity or NaN. However, there
736 // is one case we have to be careful of: The multiplier can push
737 // a number near MIN_VALUE or MAX_VALUE outside the legal range. We
738 // check for this before multiplying, and if it happens we use
739 // BigInteger instead.
740 boolean useBigInteger = false;
741 if (number < 0) { // This can only happen if number == Long.MIN_VALUE.
742 if (multiplier != 0) {
743 useBigInteger = true;
778 useExponentialNotation ? maxIntDigits + maxFraDigits : 0);
779
780 return subformat(result, delegate, isNegative, true,
781 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
782 }
783 }
784
785 /**
786 * Formats a BigDecimal to produce a string.
787 * @param number The BigDecimal to format
788 * @param result where the text is to be appended
789 * @param fieldPosition keeps track on the position of the field within
790 * the returned string. For example, for formatting
791 * a number {@code 1234567.89} in {@code Locale.US}
792 * locale, if the given {@code fieldPosition} is
793 * {@link NumberFormat#INTEGER_FIELD}, the begin index
794 * and end index of {@code fieldPosition} will be set
795 * to 0 and 9, respectively for the output string
796 * {@code 1,234,567.89}.
797 * @return The formatted number string
798 * @throws ArithmeticException if rounding is needed with rounding
799 * mode being set to RoundingMode.UNNECESSARY
800 * @see java.text.FieldPosition
801 */
802 private StringBuffer format(BigDecimal number, StringBuffer result,
803 FieldPosition fieldPosition) {
804 fieldPosition.setBeginIndex(0);
805 fieldPosition.setEndIndex(0);
806 return format(number, result, fieldPosition.getFieldDelegate());
807 }
808
809 /**
810 * Formats a BigDecimal to produce a string.
811 * @param number The BigDecimal to format
812 * @param result where the text is to be appended
813 * @param delegate notified of locations of sub fields
814 * @throws ArithmeticException if rounding is needed with rounding
815 * mode being set to RoundingMode.UNNECESSARY
816 * @return The formatted number string
817 */
818 StringBuffer format(BigDecimal number, StringBuffer result,
819 FieldDelegate delegate) {
820 if (multiplier != 1) {
821 number = number.multiply(getBigDecimalMultiplier());
822 }
823 boolean isNegative = number.signum() == -1;
824 if (isNegative) {
825 number = number.negate();
826 }
827
828 synchronized(digitList) {
829 int maxIntDigits = getMaximumIntegerDigits();
830 int minIntDigits = getMinimumIntegerDigits();
831 int maxFraDigits = getMaximumFractionDigits();
832 int minFraDigits = getMinimumFractionDigits();
833 int maximumDigits = maxIntDigits + maxFraDigits;
834
837 maxFraDigits, !useExponentialNotation);
838
839 return subformat(result, delegate, isNegative, false,
840 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
841 }
842 }
843
844 /**
845 * Format a BigInteger to produce a string.
846 * @param number The BigInteger to format
847 * @param result where the text is to be appended
848 * @param fieldPosition keeps track on the position of the field within
849 * the returned string. For example, for formatting
850 * a number {@code 123456789} in {@code Locale.US}
851 * locale, if the given {@code fieldPosition} is
852 * {@link NumberFormat#INTEGER_FIELD}, the begin index
853 * and end index of {@code fieldPosition} will be set
854 * to 0 and 11, respectively for the output string
855 * {@code 123,456,789}.
856 * @return The formatted number string
857 * @throws ArithmeticException if rounding is needed with rounding
858 * mode being set to RoundingMode.UNNECESSARY
859 * @see java.text.FieldPosition
860 */
861 private StringBuffer format(BigInteger number, StringBuffer result,
862 FieldPosition fieldPosition) {
863 fieldPosition.setBeginIndex(0);
864 fieldPosition.setEndIndex(0);
865
866 return format(number, result, fieldPosition.getFieldDelegate(), false);
867 }
868
869 /**
870 * Format a BigInteger to produce a string.
871 * @param number The BigInteger to format
872 * @param result where the text is to be appended
873 * @param delegate notified of locations of sub fields
874 * @return The formatted number string
875 * @throws ArithmeticException if rounding is needed with rounding
876 * mode being set to RoundingMode.UNNECESSARY
877 * @see java.text.FieldPosition
878 */
879 StringBuffer format(BigInteger number, StringBuffer result,
880 FieldDelegate delegate, boolean formatLong) {
881 if (multiplier != 1) {
882 number = number.multiply(getBigIntegerMultiplier());
883 }
884 boolean isNegative = number.signum() == -1;
885 if (isNegative) {
886 number = number.negate();
887 }
888
889 synchronized(digitList) {
890 int maxIntDigits, minIntDigits, maxFraDigits, minFraDigits, maximumDigits;
891 if (formatLong) {
892 maxIntDigits = super.getMaximumIntegerDigits();
893 minIntDigits = super.getMinimumIntegerDigits();
894 maxFraDigits = super.getMaximumFractionDigits();
895 minFraDigits = super.getMinimumFractionDigits();
906 }
907
908 digitList.set(isNegative, number,
909 useExponentialNotation ? maximumDigits : 0);
910
911 return subformat(result, delegate, isNegative, true,
912 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
913 }
914 }
915
916 /**
917 * Formats an Object producing an {@code AttributedCharacterIterator}.
918 * You can use the returned {@code AttributedCharacterIterator}
919 * to build the resulting String, as well as to determine information
920 * about the resulting String.
921 * <p>
922 * Each attribute key of the AttributedCharacterIterator will be of type
923 * {@code NumberFormat.Field}, with the attribute value being the
924 * same as the attribute key.
925 *
926 * @throws NullPointerException if obj is null.
927 * @throws IllegalArgumentException when the Format cannot format the
928 * given object.
929 * @throws ArithmeticException if rounding is needed with rounding
930 * mode being set to RoundingMode.UNNECESSARY
931 * @param obj The object to format
932 * @return AttributedCharacterIterator describing the formatted value.
933 * @since 1.4
934 */
935 @Override
936 public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
937 CharacterIteratorFieldDelegate delegate =
938 new CharacterIteratorFieldDelegate();
939 StringBuffer sb = new StringBuffer();
940
941 if (obj instanceof Double || obj instanceof Float) {
942 format(((Number)obj).doubleValue(), sb, delegate);
943 } else if (obj instanceof Long || obj instanceof Integer ||
944 obj instanceof Short || obj instanceof Byte ||
945 obj instanceof AtomicInteger || obj instanceof AtomicLong) {
946 format(((Number)obj).longValue(), sb, delegate);
947 } else if (obj instanceof BigDecimal) {
948 format((BigDecimal)obj, sb, delegate);
949 } else if (obj instanceof BigInteger) {
2113 * the type they want.
2114 * <li>If {@code isParseBigDecimal()} is true, values are returned
2115 * as {@code BigDecimal} objects. The values are the ones
2116 * constructed by {@link java.math.BigDecimal#BigDecimal(String)}
2117 * for corresponding strings in locale-independent format. The
2118 * special cases negative and positive infinity and NaN are returned
2119 * as {@code Double} instances holding the values of the
2120 * corresponding {@code Double} constants.
2121 * </ul>
2122 * <p>
2123 * {@code DecimalFormat} parses all Unicode characters that represent
2124 * decimal digits, as defined by {@code Character.digit()}. In
2125 * addition, {@code DecimalFormat} also recognizes as digits the ten
2126 * consecutive characters starting with the localized zero digit defined in
2127 * the {@code DecimalFormatSymbols} object.
2128 *
2129 * @param text the string to be parsed
2130 * @param pos A {@code ParsePosition} object with index and error
2131 * index information as described above.
2132 * @return the parsed value, or {@code null} if the parse fails
2133 * @throws NullPointerException if {@code text} or
2134 * {@code pos} is null.
2135 */
2136 @Override
2137 public Number parse(String text, ParsePosition pos) {
2138 // special case NaN
2139 if (text.regionMatches(pos.index, symbols.getNaN(), 0, symbols.getNaN().length())) {
2140 pos.index = pos.index + symbols.getNaN().length();
2141 return Double.valueOf(Double.NaN);
2142 }
2143
2144 boolean[] status = new boolean[STATUS_LENGTH];
2145 if (!subparse(text, pos, positivePrefix, negativePrefix, digitList, false, status)) {
2146 return null;
2147 }
2148
2149 // special case INFINITY
2150 if (status[STATUS_INFINITE]) {
2151 if (status[STATUS_POSITIVE] == (multiplier >= 0)) {
2152 return Double.valueOf(Double.POSITIVE_INFINITY);
2153 } else {
3237
3238 /**
3239 * Apply the given pattern to this Format object. A pattern is a
3240 * short-hand specification for the various formatting properties.
3241 * These properties can also be changed individually through the
3242 * various setter methods.
3243 * <p>
3244 * There is no limit to integer digits set
3245 * by this routine, since that is the typical end-user desire;
3246 * use setMaximumInteger if you want to set a real value.
3247 * For negative numbers, use a second pattern, separated by a semicolon
3248 * <P>Example {@code "#,#00.0#"} → 1,234.56
3249 * <P>This means a minimum of 2 integer digits, 1 fraction digit, and
3250 * a maximum of 2 fraction digits.
3251 * <p>Example: {@code "#,#00.0#;(#,#00.0#)"} for negatives in
3252 * parentheses.
3253 * <p>In negative patterns, the minimum and maximum counts are ignored;
3254 * these are presumed to be set in the positive pattern.
3255 *
3256 * @param pattern a new pattern
3257 * @throws NullPointerException if {@code pattern} is null
3258 * @throws IllegalArgumentException if the given pattern is invalid.
3259 */
3260 public void applyPattern(String pattern) {
3261 applyPattern(pattern, false);
3262 }
3263
3264 /**
3265 * Apply the given pattern to this Format object. The pattern
3266 * is assumed to be in a localized notation. A pattern is a
3267 * short-hand specification for the various formatting properties.
3268 * These properties can also be changed individually through the
3269 * various setter methods.
3270 * <p>
3271 * There is no limit to integer digits set
3272 * by this routine, since that is the typical end-user desire;
3273 * use setMaximumInteger if you want to set a real value.
3274 * For negative numbers, use a second pattern, separated by a semicolon
3275 * <P>Example {@code "#,#00.0#"} → 1,234.56
3276 * <P>This means a minimum of 2 integer digits, 1 fraction digit, and
3277 * a maximum of 2 fraction digits.
3278 * <p>Example: {@code "#,#00.0#;(#,#00.0#)"} for negatives in
3279 * parentheses.
3280 * <p>In negative patterns, the minimum and maximum counts are ignored;
3281 * these are presumed to be set in the positive pattern.
3282 *
3283 * @param pattern a new pattern
3284 * @throws NullPointerException if {@code pattern} is null
3285 * @throws IllegalArgumentException if the given pattern is invalid.
3286 */
3287 public void applyLocalizedPattern(String pattern) {
3288 applyPattern(pattern, true);
3289 }
3290
3291 /**
3292 * Does the real work of applying a pattern.
3293 */
3294 private void applyPattern(String pattern, boolean localized) {
3295 char zeroDigit = PATTERN_ZERO_DIGIT;
3296 char groupingSeparator = PATTERN_GROUPING_SEPARATOR;
3297 char decimalSeparator = PATTERN_DECIMAL_SEPARATOR;
3298 char percent = PATTERN_PERCENT;
3299 char perMill = PATTERN_PER_MILLE;
3300 char digit = PATTERN_DIGIT;
3301 char separator = PATTERN_SEPARATOR;
3302 String exponent = PATTERN_EXPONENT;
3303 char minus = PATTERN_MINUS;
3304 if (localized) {
3305 zeroDigit = symbols.getZeroDigit();
3765 * {@link DecimalFormatSymbols#getCurrency DecimalFormatSymbols.getCurrency}
3766 * on this number format's symbols.
3767 *
3768 * @return the currency used by this decimal format, or {@code null}
3769 * @since 1.4
3770 */
3771 @Override
3772 public Currency getCurrency() {
3773 return symbols.getCurrency();
3774 }
3775
3776 /**
3777 * Sets the currency used by this number format when formatting
3778 * currency values. This does not update the minimum or maximum
3779 * number of fraction digits used by the number format.
3780 * The currency is set by calling
3781 * {@link DecimalFormatSymbols#setCurrency DecimalFormatSymbols.setCurrency}
3782 * on this number format's symbols.
3783 *
3784 * @param currency the new currency to be used by this decimal format
3785 * @throws NullPointerException if {@code currency} is null
3786 * @since 1.4
3787 */
3788 @Override
3789 public void setCurrency(Currency currency) {
3790 if (currency != symbols.getCurrency()) {
3791 symbols.setCurrency(currency);
3792 if (isCurrencyFormat) {
3793 expandAffixes();
3794 }
3795 }
3796 fastPathCheckNeeded = true;
3797 }
3798
3799 /**
3800 * Gets the {@link java.math.RoundingMode} used in this DecimalFormat.
3801 *
3802 * @return The {@code RoundingMode} used for this DecimalFormat.
3803 * @see #setRoundingMode(RoundingMode)
3804 * @since 1.6
3805 */
3806 @Override
3807 public RoundingMode getRoundingMode() {
3808 return roundingMode;
3809 }
3810
3811 /**
3812 * Sets the {@link java.math.RoundingMode} used in this DecimalFormat.
3813 *
3814 * @param roundingMode The {@code RoundingMode} to be used
3815 * @see #getRoundingMode()
3816 * @throws NullPointerException if {@code roundingMode} is null.
3817 * @since 1.6
3818 */
3819 @Override
3820 public void setRoundingMode(RoundingMode roundingMode) {
3821 if (roundingMode == null) {
3822 throw new NullPointerException();
3823 }
3824
3825 this.roundingMode = roundingMode;
3826 digitList.setRoundingMode(roundingMode);
3827 fastPathCheckNeeded = true;
3828 }
3829
3830 /**
3831 * Reads the default serializable fields from the stream and performs
3832 * validations and adjustments for older serialized versions. The
3833 * validations and adjustments are:
3834 * <ol>
3835 * <li>
3836 * Verify that the superclass's digit count fields correctly reflect
|